<?php

namespace app\index\controller;

use app\common\model\Test;
use think\Db;
use think\Exception;

class User extends Base
{
    /**
     * 获取用户位置
     */
    public function getUserPosition()
    {
        if (!input('latitude')) {
            $this->err('缺少latitude');
        }
        if (!input('longitude')) {
            $this->err('缺少longitude');
        }
        $latitude = input('latitude');
        $longitude = input('longitude');
        //百度API
        $bdApi = 'http://api.map.baidu.com/geocoder/v2/?ak=' . config('ak') . '&location=' . $latitude . ',' . $longitude . '&output=json&pois=1';
        $data = sendRequest($bdApi);
        $dataArray = json_decode($data, true);
        if ($dataArray['status'] == 0) {
            $res = [
                'address' => $dataArray['result']['formatted_address'],
                'location' => $dataArray['result']['location'],
                'addressComponent' => $dataArray['result']['addressComponent']
            ];
            $this->suc($res);
        } else {
            $this->err('百度api调取失败！！！');
        }
    }

    /**
     * 获取用户openid
     */
    public function getOpenid()
    {

        $wechat = config('wechat');

        $js_code = input('code');
        if (empty($js_code)) {
            $this->err('缺少code！');
        }
        
        $appid = $wechat['AppId'];
        $appsecret = $wechat['AppSecret'];
        $curl = 'https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code';
        $curl = sprintf($curl, $appid, $appsecret, $js_code);
        $result = sendRequest($curl);
        $result = json_decode($result, true);
        $res = [];
        if (array_key_exists('openid', $result)) {
            $res['openid'] = $result['openid'];
        } else {
            $this->err('获取用户openid错误！');
        }

        if (array_key_exists('session_key', $result)) {

            $res['session_key'] = $result['session_key'];

        } else {

            $this->err('获取用户session_key错误！');

        }

        $this->suc($res);
    }

    /**
     * 二维码
     */
    public function qrCode()
    {

        $cid = 0;
        input('cid') ? $cid = input('cid') : $this->err('缺少用户主键！');
        $user_cid = model('user')->where(['id' => $cid])->count();
        if (!$user_cid) {
            $this->err('用户编码错误！');
        }
        $AppId = config('wechat.AppId');
        $AppSecret = config('wechat.AppSecret');
        // 小程序二维码 A
        $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . $AppId . '&secret=' . $AppSecret;

        $res = sendRequest($url);
        $token = json_decode($res)->access_token;

        $path = "example/home/index?cid=" . $cid;

        //$path = json($path, true);
        header('content-type:image/png');

        // 小程序二维码 A
        $url = 'https://api.weixin.qq.com/wxa/getwxacode?access_token=' . $token;

        // 小程序二维码 B
        //$url='https://api.weixin.qq.com/wxa/getwxacode?access_token='.$token;

        $data = [
            'width' => 400,
            'path' => $path
        ];
        $rep = curlPost($url, $data);
        if (!$rep) {
            $this->err('获取失败！');
        }
        //查询用户有没有二维码
        $user = model('user')->field('qrCode')->where(['id' => $cid])->find();
        if ($user['qrCode']) {
            $this->suc($user);
        } else {
            //echo (base64_encode($rep));
            $base64_code = 'data:' . 'image/png' . ';base64,' . base64_encode($rep);
            $code = model('user')->where(['id' => $cid])->update(['qrCode' => $base64_code]);
            if (!$code) {
                $this->err('保存二维码失败！');
            }
            $this->suc($base64_code);
        }
    }

    /**
     * 消息模板
     */
    public function messageTemplate()
    {
        /*$tmp = new Test();
        dump($tmp->keyword1);exit;*/

        $data = [];
        $type = 0;
        input('openid') ? $data['touser'] = input('openid') : $this->err('缺少用户openid！');
        input('formId') ? $data['formId'] = input('formId') : $this->err('缺少formId！');
        input('data') ? $data['data'] = input('data') : true;
        input('templateId') ? $data['templateId'] = input('templateId') : $this->err('缺少templated！');
        input('page') ? $data['page'] = input('page') : $this->err('缺少page！');
        input('modelType') ? $type = input('modelType') : $this->err('缺少type！');


        //当前时间戳
        $now = time();

        if ($type == 1) { //注册
            $time = 180;
        } elseif ($type == 2) { // 2-购买月卡
            input('orderSn') ? $orderSn = input('orderSn') : $this->err('缺少orderSn！');
            input('content') ? $content = input('content') : $this->err('缺少content！');
            $order = model('order')->where(['orderSn' => $orderSn])->find();

            $data['data'] = '{"keyword1":{"value":"2018-08-27 12:07:27"},"keyword2":{"value":"\u60a8\u5df2\u6210\u529f\u70b9\u4eae\u6807\u793a"},"keyword3":{"value":"XB15353428466095235"},"keyword4":{"value":"100.00"}}';

            $dat = json_decode($data['data']);
            $order = model('order')->where(['orderSn' => $orderSn])->find();
            $dat->keyword1->value = $order['payTime'];
            $dat->keyword2->value = $content;
            $dat->keyword3->value = $orderSn;
            $dat->keyword4->value = $order['totalAmount'];
            $data['data'] = json_encode($dat);

            $time = 3600;

            /*$dat=json_decode($data['data']);
            $order=model('order')->where(['orderSn'=>$dat->keyword2->value])->find();
            $dat->keyword1->value=$order['payTime'];
            $dat->keyword3->value=$order['orderSn'];
            $dat->keyword4->value=$order['totalAmount'];*/

        } elseif ($type == 3) { //3-发布需求后领取优惠券通知
            $time = 3600;
        } else {
            $this->err('modelType错误！');
        }

        $data['createTime'] = date('Y-m-d H:i:s', $now + $time);


        $res = model('message_template')->insert($data);

        $res ? $this->suc($res) : $this->err('添加失败！');
    }

    public function sendMsgLater()
    {
        $where = [];
        $where['isRelease'] = 0;

        $now = time();

        $where['createTime'] = ['< time', $now];


        $messageTemplate = model('message_template')->where($where)->select();

        $AppId = config('wechat.AppId');
        $AppSecret = config('wechat.AppSecret');

        $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . $AppId . '&secret=' . $AppSecret;

        $res = sendRequest($url);
        $token = json_decode($res)->access_token;
        $url = 'https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=' . $token;

        foreach ($messageTemplate as $value) {
            $data = [
                'touser' => $value['touser'],
                'form_id' => $value['formId'],
                'data' => json_decode($value['data']),
                'template_id' => $value['templateId'],
                'page' => $value['page']
            ];
            $rep = curlPostWx($url, $data);
            /*if (!$rep) {
                Log::record('发送失败！', 'error');
                exit;
            }*/
            $status = model('message_template')->where(['id' => $value['id']])->update(['isRelease' => 1]);
            /* if (!$status) {
                 Log::record('状态修改失败！', 'error');
                 exit;
             }*/
        }

        $this->suc(createTime());
    }

    /**
     * 获取用户access_token
     */

    public function getAccessToken()
    {
        $AppId = config('wechat.AppId');
        $AppSecret = config('wechat.AppSecret');
        $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . $AppId . '&secret=' . $AppSecret;
        $res = sendRequest($url);
        $this->suc($res);
    }

    public function login()
    {
        $request = request();
        $where = [];
        input('mobile') ? $where['mobile'] = input('mobile') : $this->err('缺少手机号！');
        input('password') ? $where['password'] = md5(input('password')) : $this->err('缺少密码！');
        //上级用户主键
        input('cid') ? $cid = input('cid') : true;

        $field = 'password, payPwd,uid';
        $member = model('user')->where($where)->field($field, true)->find();
        if (empty($member)) {
            $this->err('手机或密码错误！');
        }
        if ($member['userStatus'] == 0) {
            $this->err('该用户未激活，请先激活！');
        }
        if ($member['userStatus'] == -1) {
            $this->err('该用户已被冻结，请联系管理员！');
        }
        if ($member['userType'] != 2) {
            $this->err('该用户不是管理员，无法登陆后台！');
        }
        $token = md5($member['id'] + time());
                S("u" . $member['id'], $token, 60 * 60 * 24 * 30);
                 session('token', $token);

        //当前时间戳
        $now = time();
        $vipTime = 3 * 86400;
        $vipEndTime = $now + $vipTime;
        //第一次登陆送三天vip
        if (!$member['lastLoginTime']) {
            $data['vipEndTime'] = date('Y-m-d  H : i :s ', $vipEndTime);
            if ($cid) {
                $data['leaderId'] = $cid;
                //查询上级用户的魅力分
                $leader_res = model('user')->field('inviteCount,charm')->where($cid)->find();
                //查询系统配置
                $sy = model('system_config')->where(['status' => 1])->find();
                $sy ? true : $this->err('查询系统配置失败！');
                //获取邀请朋友分值+上级的魅力
                $charm = $sy['friendInviteValue'] + $leader_res['charm'];
                //用户表更新数据
                $u_data = [
                    'id' => $cid,
                    'charm' => $charm,
                    'inviteCount' => $leader_res['inviteCount'] + 1
                ];
                //查询用户魅力表数据
                $uc_res = model('user')->field('friendInvite,friendInvitePoints')->where(['cid' => $cid])->find();
                //用户魅力表跟新数据
                $uc_data = [
                    'cid' => $cid,
                    'friendInvite' => $uc_res['friendInvite'] + 1,
                    'friendInvitePoints' => $uc_res['friendInvitePoints'] + $sy['friendInviteValue']
                ];
                model('user_charm')->where(['cid' => $cid])->update($uc_data);
                //新增魅力分日志
                $l = model('user')->editScore($cid, 1, $sy['friendInviteValue'], 1, 8);
                $l ? true : $this->err('新增魅力值日志失败！');
            }


        }
        //更新用户表
        $data = [
            'lastLoginTime' => createTime(),
            'lastIP' => $request->ip()
        ];
        model('user')->editData($data, $member['id']);
        $rep = ['userInfo' => $member, 'token' => $token];
        $this->suc($rep);
    }

    /**
     * 验证手机号是否重复
     * 0-未注册 1已注册过
     */
    public function verificationMobile()
    {
        $data = [];
        input('mobile') ? $data['mobile'] = input('mobile') : $this->err('缺少手机号！');
        $mobile = model('user')->where(['mobile' => $data['mobile']])->count();
        if (!checkMobile($data['mobile'])) {
            $this->err('手机号不正确！');
        }
        if ($mobile) {
            $this->suc('1');
        } else {
            $this->suc('0');
        }
    }

    /**
     * 验证身份证是否重复
     * 0-未注册 1已注册过
     */
    public function verificationIDCards()
    {
        $data = [];
        input('IDCards') ? $data['IDCards'] = input('IDCards') : $this->err('缺少身份证号！');
        $IDCards = model('user')->where(['IDCards' => $data['IDCards']])->count();
        //身份证格式验证
        if (!checkIDCard($data['IDCards'])) {
            $this->err('身份证号不正确！');
        }
        if ($IDCards) {
            $this->suc('1');
        } else {
            $this->suc('0');
        }
    }

    /**
     * 判断是否注册
     * 0-未注册 1已注册过
     */
    public function isRegister()
    {
        $where = [];
        input('openid') ? $where['openid'] = input('openid') : $this->err('缺少用户主键！');
        $user = model('user')->where($where)->find();
        if ($user) {
            $this->suc('1');
        }
        if (!$user) {
            $this->suc('0');
        }

    }

    /**
     * 注册
     * $category   1-微信注册 2-手机号注册
     */
    public function register()
    {
        $data = [];

        input('category') ? $category = input('category') : $this->err('缺少选择方式');

        input('openid') ? $data['openid'] = input('openid') : $this->err('缺少用户主键！');
        input('latitude') ? $latitude = (float)input('latitude') : $this->err('缺少纬度！');
        input('longitude') ? $longitude = (float)input('longitude') : $this->err('缺少经度！');
        input('mobile') ? $data['mobile'] = input('mobile') : $this->err('缺少手机号！');
        input('name') ? $data['name'] = input('name') : $this->err('缺少姓名！');
        input('userType') ? $data['userType'] = input('userType') : $this->err('缺少用户类型！');
        input('avatar') ? $data['avatar'] = input('avatar') : $this->err('缺少头像！');
        input('cid') ? $cid = input('cid') : true;
        $data['createTime'] = createTime();
        if (!checkMobile($data['mobile'])) {
            $this->err('手机号不正确！');
        }

        if($category==2){

            input('code') ? $code = input('code') : $this->err('缺少验证码！');

            if (!$code || $code != cache('m' . $data['mobile'])) {
                $this->err('验证码错误！');
            }

        }

        $isRegister = model('user')->where(['mobile' => $data['mobile']])->count();
        if ($isRegister) {
            $this->err('该手机已被注册！');
        }
        /*  if (!checkIDCard($data['IDCards'])) {
              $this->err('身份证号不正确！');
          }*/
        //当前时间戳
        /*    $now = time();
            $vipTime = 3 * 86400;
            $vipEndTime = $now + $vipTime;
            //注册送三天vip
            $data['vipEndTime'] = date('Y-m-d H:i:s', $vipEndTime);*/

        Db::startTrans();
        //启动数据库事务
        try {
            //查询系统配置
            $sy = model('system_config')->where(['status' => 1])->find();
            $sy ? true : $this->err('查询系统配置失败！');

            //根据经纬度查询地址
            $position = model('user')->getUserPosition($latitude, $longitude);
            $position = $position['content'];
            $position = $position['addressComponent'];

            $data['province'] = $position['province'];
            $data['city'] = $position['city'];
            $data['district'] = $position['district'];
            $data['street'] = $position['street'];
            $data['latitude'] = $latitude;
            $data['longitude'] = $longitude;
            $data['dataPercent'] = 0.50;
            $data['charm'] = $sy['dataValue'] / 2;


            //如果用户是被邀请过来
            if (input('cid')) {
                $data['leaderId'] = input('cid');
                //把新用户添加到用户表中

                $res = model('user')->editData($data);

                $dataPercent = [
                    'cid' => $res,
                    'dataPercent' => 0.50,
                    'dataPoints' => $sy['dataValue'] / 2
                ];
                model('user_charm')->editData($dataPercent);
                //新增魅力分日志
                $charm_log = [
                    'sign' => 1,
                    'cid' => $res,
                    'source' => 5,
                    'score' => $sy['dataValue'] / 2,
                    'leftScore' => $sy['dataValue'] / 2,
                    'inviteCid' => '',
                    'createTime' => createTime()
                ];

                //查询上级用户的魅力分
                $leader_res = model('user')->field('inviteCount,charm')->where(['id' => input('cid')])->find();
                //获取邀请朋友分值+上级的魅力
                $charm = $sy['friendInviteValue'] + $leader_res['charm'];

                //上级用户更新用户表数据
                $u_data = [
                    'id' => input('cid'),
                    'charm' => $charm,
                    'inviteCount' => $leader_res['inviteCount'] + 1
                ];
                //更新上级用户表数据
                model('user')->where(['id' => input('cid')])->update($u_data);
                //查询上级用户魅力表数据
                $uc_res = model('user_charm')->field('friendInvite,friendInvitePoints')->where(['cid' => input('cid')])->find();

                //上级用户魅力表数据更新
                $uc_data = [
                    'cid' => input('cid'),
                    'friendInvite' => $uc_res['friendInvite'] + 1,
                    'friendInvitePoints' => $uc_res['friendInvitePoints'] + $sy['friendInviteValue']
                ];
                model('user_charm')->where(['cid' => input('cid')])->update($uc_data);

                //新增上级用户魅力分日志数据
                $log_data = [
                    'sign' => 1,
                    'cid' => input('cid'),
                    'source' => 8,
                    'score' => $sy['friendInviteValue'],
                    'inviteCid' => $res,
                    'leftScore' => $charm,
                    'createTime' => createTime()
                ];
                //批量新增-上级用户和用户在日志表的数据
                $charm_log_data = [
                    $log_data,
                    $charm_log
                ];
                $l = model('user_charm_log')->saveAll($charm_log_data);

                $l ? true : $this->err('新增魅力值日志失败！');

            } else {
                $res = model('user')->editData($data);
                //注册完成时默认资料完善程度为50%
                $dataPercent = [
                    'cid' => $res,
                    'dataPercent' => 0.50,
                    'dataPoints' => $sy['dataValue'] / 2
                ];
                model('user_charm')->editData($dataPercent);
                //新增魅力分日志
                $charm_log = [
                    'sign' => 1,
                    'cid' => $res,
                    'source' => 5,
                    'score' => $sy['dataValue'] / 2,
                    'leftScore' => $sy['dataValue'] / 2,
                    'createTime' => createTime()
                ];
                model('user_charm_log')->editData($charm_log);
            }

            //提交事务
            if ($res) {
                Db:: commit();
                $this->suc($res);
            } else {
                Db::rollback();
                $this->err('注册失败！');
            }
        } catch (\Exception $e) {
            Db::rollback();
            $this->err('操作失败！');
        }
    }

    /**
     * 完善信息
     */
    public function perfectInformation()
    {
        $data = [];
        input('cid') ? $data['id'] = input('cid') : $this->err('缺少用户主键！');
        input('jobId') ? $data['job'] = input('jobId') : $this->err('缺少岗位');

        $res = model('user')->editData($data, $data['id']);
        $res ? $this->suc($res) : $this->err('完善信息失败！');
    }

    public function addUser()
    {
        $data = [];
        $data['name'] = input('name');
        $data['password'] = input('password');
        $data['mobile'] = input('mobile');
        $data['IDCards'] = input('IDCards');
        $data['isGoodEmployer'] = input('isGoodEmployer');
        $data['avatar'] = input('avatar');
        $data['province'] = input('province');
        $data['city'] = input('city');
        $data['district'] = input('district');
        $data['street'] = input('street');

        $result = $this->validate($data, 'User');
        if ($result !== true) {
            $this->err($result);
        }
        $data['password'] = md5($data['password']);

        //删除空的字段
        foreach ($data as $key => $value) {
            if (empty($value)) {
                unset($data['$key']);
            }
        }

        $res = model('user')->editData($data);
        $res ? $this->suc($res) : $this->err('添加用户出错！');
    }

    public function editUser()
    {
        $data = [];
        $data['id'] = input('cid');
        $data['name'] = input('name');
        $data['password'] = input('password');
        $data['mobile'] = input('mobile');
        $data['IDCards'] = input('IDCards');
        $data['isGoodEmployer'] = input('isGoodEmployer');
        $data['avatar'] = input('avatar');
        $data['province'] = input('province');
        $data['city'] = input('city');
        $data['district'] = input('district');
        $data['street'] = input('street');
        $data['uid'] = input('uid') ? input('uid') : 1;

        if (empty($data['id'])) {
            $this->err('缺少用户主键！');
        }

        $result = $this->validate($data, 'User');
        if ($result !== true) {
            $this->err($result);
        }

        //删除空的字段
        foreach ($data as $key => $value) {
            if (empty($value)) {
                unset($data['$key']);
            }
        }

        $res = model('user')->editData($data, $data['id'], $data['uid']);
        if ($res == 0 || $res) {
            $this->suc($res);
        } else {
            $this->err('修改用户出错！');
        }
    }

    /**
     * 修改阿姨信息需求
     */
    public function editWorkInfo()
    {
        $data = [];

        input('cid') != null ? $data['id'] = input('cid') : $this->err('缺少阿姨编码！');
        input('age') != null ? $data['age'] = input('age') : $this->err('缺少年龄！');
        input('jobId') != null ? $data['job'] = input('jobId') : $this->err('缺少工种！');
        input('beginTime') != null ? $data['beginTime'] = input('beginTime') : $this->err('缺少工作开始时间！');
        input('endTime') != null ? $data['endTime'] = input('endTime') : $this->err('缺少工作结束时间！');
        input('workYear') != null ? $data['workYear'] = input('workYear') : $this->err('缺少工作年限！');
        input('workDuty') != null ? $data['workDuty'] = input('workDuty') : $this->err('缺少工作职责！');
//        input('jobSalary')!=null ? $data['salary'] = input('jobSalary') : $this->err('缺少工资要求！');
        input('maxSalary') != null ? $data['maxSalary'] = input('maxSalary') : $this->err('缺少最大岗位工资！');
        input('minSalary') != null ? $data['minSalary'] = input('minSalary') : $this->err('缺少最小岗位工资！');
        input('rest') != null ? $data['rest'] = input('rest') : $this->err('缺少月休！');
        input('legalRest') != null ? $data['legalRest'] = input('legalRest') : $this->err('缺少法定休息！');
        input('appearance') != null ? $data['appearance'] = input('appearance') : $this->err('缺少个人形象');
        input('province') != null ? $data['province'] = input('province') : $this->err('缺少地址！');
        input('city') != null ? $data['city'] = input('city') : $this->err('缺少地址！');
        input('district') != null ? $data['district'] = input('district') : $this->err('缺少地址！');
        input('street') != null ? $data['street'] = input('street') : $this->err('缺少地址！');
        $data['isPushExpect'] = 1;

        $user = model('user')->where(['id' => input('cid')])->find();
        if ($user['isPushExpect'] == 0) {

            Db::startTrans();
            //启动数据库事务
            try {
                $sy = model('system_config')->where(['status' => 1])->find();
                $sy ? true : $this->err('查询系统配置失败！');
                //用户第一次发布需求时增加魅力分
                $data['charm'] = $sy['dataValue'];
                $data['dataPercent'] = 1.00;
                $res = model('user')->editData($data, $data['id']);
                //更新用户魅力表数据
                $dataPercent = [
                    'cid' => input('cid'),
                    'dataPercent' => 1.00,
                    'dataPoints' => $sy['dataValue']
                ];
                model('user_charm')->where(['cid' => input('cid')])->update($dataPercent);
                //新增魅力分日志
                $charm_log = [
                    'sign' => 1,
                    'cid' => input('cid'),
                    'source' => 5,
                    'score' => $sy['dataValue'] / 2,
                    'leftScore' => $sy['dataValue'],
                    'createTime' => createTime()
                ];
                model('user_charm_log')->editData($charm_log);
                //提交事务
                if ($res) {
                    Db:: commit();
                    $this->suc($res);
                } else {
                    Db::rollback();
                    $this->err('发布失败！');
                }
            } catch (\Exception $e) {
                Db::rollback();
                $this->err('操作失败！');
            }
        } else {
            $res = model('user')->editData($data, $data['id']);
            $res ? $this->suc($res) : $this->err('缺少修改内容！');
        }
    }

    /**
     * 修改用户信息
     */
    public function editUserInfo()
    {

        $data = [];

        input('openid') ? $data['openid'] = input('openid') : $this->err('缺少用户主键！');
        //用户姓名
        input('name') ? $data['name'] = input('name') : $this->err('缺少姓名！');
        //地址
        input('province') ? $data['province'] = input('province') : $this->err('缺少地址！');
        //地址
        input('city') ? $data['city'] = input('city') : $this->err('缺少地址！');
        //地址
        input('district') ? $data['district'] = input('district') :$this->err('缺少地址！');
        //地址
        input('street') ? $data['street'] = input('street') : $this->err('缺少地址！');
        //手机号
        input('mobile') ? $data['mobile'] = input('mobile') : $this->err('缺少手机号！');

        input('isOpenFollow') || input('isOpenFollow') == 0 ? $data['isOpenFollow'] = input('isOpenFollow') : true;
        input('isOpenChat') || input('isOpenChat') == 0 ? $data['isOpenChat'] = input('isOpenChat') : true;
        input('isHiddenMobile') || input('isHiddenMobile') == 0 ? $data['isHiddenMobile'] = input('isHiddenMobile') : true;
        input('IDCards') ? $data['IDCards'] = input('IDCards') : $this->err('缺少身份证号！');
        $mobile = model('user')->where(['mobile' => $data['mobile'], 'openid' => ['<>', $data['openid']]])->count();
        $IDCards = model('user')->where(['IDCards' => $data['IDCards'], 'openid' => ['<>', $data['openid']]])->count();
        if ($mobile) {
            $this->err('该手机号已被其他用户注册！');
        }
        $user = model('user')->where(['openid' => $data['openid']])->find();
        if ($user['mobile'] != $data['mobile']) {
            input('code') ? $code = input('code') : $this->err('缺少验证码！');
            if (!checkMobile($data['mobile'])) {
                $this->err('手机号不正确！');
            }
            if (!$code || $code != cache('m' . $data['mobile'])) {
                $this->err('验证码错误！');
            }
        }
        if ($IDCards) {
            $this->err('该身份证号已被注册！');
        }
        if (!checkIDCard($data['IDCards'])) {
            $this->err('身份证号不正确！');
        }

        $count = model('user')->where(['openid' => $data['openid']])->count();

        if (!$count) {
            $this->err('openid错误！');
        }
        //查询用户cid
        $cid = model('user')->where(['openid' => $data['openid']])->find();
        $expect_data = [
            'cid' => $cid['id'],
            'province' => $data['province'],
            'city' => $data['city'],
            'street' => $data['street']
        ];
        if (!empty($data['district'])) {
            $expect_data['district'] = $data['district'];
        }

        // 启动事务
        Db::startTrans();
        try {
            if ($cid['userType'] == 1) {
                model('user_expect')->where(['cid' => $cid['id']])->update($expect_data);
            }
            $res = model('user')->where(['openid' => $data['openid']])->update($data);
            // 提交事务
            if ($res) {
                Db::commit();
                $this->suc($res);
            } else {
                Db::rollback();
                $this->err('修改失败');
            }
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            //   $this->err($e);
            $this->err('操作失败！');
        }
    }

    /**
     * 用户详情
     */
    public function getUserDetail()
    {
        $where = [];
        $a_where = [];
        input('cid') ? $cid = input('cid') : true;
        input('openid') ? $openid = input('openid') : true;

        if (empty($cid) && empty($openid)) {
            $this->err('缺少用户主键！');
        }
        if (input('openid') && input('cid')) {
            $this->err('只能存在一个主键！');
        }
        if (empty($cid)) {
            $where['u.openid'] = input('openid');
            $a_where['u.openid'] = input('openid');

        } else {
            $where['u.id'] = input('cid');
            $a_where['u.id'] = input('cid');
        }
        $user = model('user')->alias('u')->field('id, userType')->where($where)->find();
        if ($user['userType'] == 1) {
            $res = model('user')
                ->alias('u')
                ->field('u.*,j.name as jobName')
                ->join('user_expect ue', 'ue.cid=u.id', 'left')
                ->join('job j', 'ue.jobId=j.id', 'left')
                ->where($where)
                ->find();
            $count = model('user_relation')->where(['employeeId' => $user['id']])->where(function ($query) {
                $query->where(['isFollow' => 1])->whereor(['isFollow' => 3]);
            })->count();
        } else {
            $res = model('user')
                ->alias('u')
                ->field('u.*,j.name as jobName')
                ->join('job j', 'u.job=j.id', 'left')
                ->where($a_where)
                ->find();

            $count = model('user_relation')->where(['workId' => $user['id']])->where(function ($query) {
                $query->where(['isFollow' => 2])->whereor(['isFollow' => 3]);
            })->count();
        }

        $res ? true : $this->err('查询失败！');

        if ($count == null) {
            $count = 0;
        }

        //查询用户优惠券数量
        $c_where = [
            'cid' => $res['id'],
            'status' => 1,
            'overTime' => ['> time', time()],

        ];
        $couponCount = model('userCoupon')->where($c_where)->count();
        $res['couponCount'] = $couponCount;
        $res['followCount'] = $count;
        $res ? $this->suc($res) : $this->err('获取用户详情出错！');

    }

    /**
     * 修改客户需求任务
     */
    public function editUserExpect()
    {
        $data = [];

        $u_data = [];

        input('cid') ? $data['cid'] = input('cid') : $this->err('缺少用户主键！');

        //年龄限制
        input('ageStart') ? $data['ageStart'] = input('ageStart') : $this->err('缺少年龄限制！');
        //年龄限制
        input('ageEnd') ? $data['ageEnd'] = input('ageEnd') : $this->err('缺少年龄限制！');
        //工种
        input('jobId') ? $data['jobId'] = input('jobId') : $this->err('缺少工种！');
        //工作开始时间
        input('beginTime') ? $data['beginTime'] = input('beginTime') : $this->err('缺少工作开始时间！');
        //工作结束时间
        input('endTime') ? $data['endTime'] = input('endTime') : $this->err('缺少工作结束时间！');
        //工作年限
        input('workyearStart') != null ? $data['workyearStart'] = input('workyearStart') : $this->err('缺少工作年限！');
        //工作年限
        input('workyearEnd') != null ? $data['workyearEnd'] = input('workyearEnd') : $this->err('缺少工作年限！');
        //工作职责
        input('workDuty') ? $data['workDuty'] = input('workDuty') : $this->err('缺少工作职责！');
        //形象
        input('appearance') ? $data['appearance'] = input('appearance') : $this->err('缺少形象！');
        //最大岗位工资
        input('maxSalary') != null ? $data['maxSalary'] = input('maxSalary') : $this->err('缺少最大岗位工资！');
        //最小岗位工资
        input('minSalary') != null ? $data['minSalary'] = input('minSalary') : $this->err('缺少最小岗位工资！');
        //月休
        input('rest') != null ? $data['rest'] = input('rest') : $this->err('缺少月休！');
        //法定休息
        input('legalRest') != null ? $data['legalRest'] = input('legalRest') : $this->err('缺少法定休息！');
        //地址
        input('province') ? $data['province'] = input('province') : $this->err('缺少地址！');
        //地址
        input('city') ? $data['city'] = input('city') : $this->err('缺少地址！');
        //地址
        input('district') ? $data['district'] = input('district') : $this->err('缺少地址！');
        //地址
        input('street') ? $data['street'] = input('street') : $this->err('缺少地址！');

        // 判断该用户是否发布过需求
        $count = model('userExpect')->where(['cid' => $data['cid']])->count();
        //没有发布执行新增操作
        if ($count == 0) {
            Db::startTrans();
            //启动数据库事务
            try {
                $sy = model('system_config')->where(['status' => 1])->find();
                $sy ? true : $this->err('查询系统配置失败！');
                // 新增操作
                $u_data = [
                    'isPushExpect' => 1,
                    'id' => $data['cid'],
                    //用户第一次发布需求时增加魅力分
                    'charm' => $sy['dataValue'],
                    'dataPercent' => 1.00,
                    'province' => $data['province'],
                    'city' => $data['city'],
                    'street' => $data['street']
                ];
                if (!empty($data['district'])) {
                    $u_data['district'] = $data['district'];
                }
                //更新用户表数据
                model('user')->editData($u_data, $u_data['id']);
                //新增用户需求表数据
                $res = model('userExpect')->editData($data);

                //更新用户魅力表数据
                $dataPercent = [
                    'cid' => input('cid'),
                    'dataPercent' => 1.00,
                    'dataPoints' => $sy['dataValue']
                ];
                model('user_charm')->where(['cid' => input('cid')])->update($dataPercent);
                //新增魅力分日志
                $charm_log = [
                    'sign' => 1,
                    'cid' => input('cid'),
                    'source' => 5,
                    'score' => $sy['dataValue'] / 2,
                    'leftScore' => $sy['dataValue'],
                    'createTime' => createTime()
                ];
                model('user_charm_log')->editData($charm_log);
                //提交事务
                if ($res) {
                    Db:: commit();
                    $this->suc('发布成功！');
                } else {
                    Db::rollback();
                    $this->err('发布失败！');
                }
            } catch (\Exception $e) {
                Db::rollback();
                $this->err('操作失败！');
            }

        } else {
            $u_data = [
                'id' => $data['cid'],
                'province' => $data['province'],
                'city' => $data['city'],
                'street' => $data['street']
            ];
            if (!empty($data['district'])) {
                $u_data['district'] = $data['district'];
            }
            model('user')->editData($u_data, $u_data['id']);
            $res = model('userExpect')->where(['cid' => input('cid')])->update($data);
            $res ? $this->suc($res) : $this->err('请输入修改内容！');
        }

    }

    /**
     * 获取客户需求
     */
    public function getUserExpect()
    {
        $where = [];
        input('cid') ? $where['cid'] = input('cid') : $this->err('缺少用户编码！');

        $res = model('userExpect')
            ->alias('ue')
            ->field('ue.*,j.name as jobName,j.jobSalary')
            ->join('job j', 'j.id=ue.jobId', 'left')
            ->where($where)
            ->find();
        $res ? $this->suc($res) : $this->err('查询错误！');
    }

    /**
     * 获取收藏列表
     */
    public function getUserCollectList()
    {
        $where = [];
        input('cid') ? $where['ua.cid'] = input('cid') : $this->err('缺少用户主键');
        $where['isCollect'] = 1;
        $res = model('user_article')
            ->alias('ua')
            ->field('a.*,ua.isCollect')
            ->join('article a', 'ua.articleId=a.id', 'left')
            ->where($where)
            ->paginate(10)
            ->toArray();
        $res ? $this->suc($res) : $this->err('获取点赞列表失败');
    }

    /**
     * 获取推荐好友列表
     */
    public function getUserFriendList()
    {
        $where = [];
        $data = [];
        //    $field = 'name,avatar,mobile,userType,charm,province,city,district,street';
        input('cid') ? $data['id'] = input('cid') : $this->err('缺少用户主键');
        $where['leaderId'] = $data['id'];

        $res = model('user')->getListByPage($where, 10);
        $res ? $this->suc($res) : $this->err('获取我的推荐好友失败！');

    }

    /**
     * 充值
     */
    public function rechargeMoney()
    {
        $data = [];

        input('cid') ? $data['cid'] = input('cid') : $this->err('缺少用户主键！');
        input('rechargeMoney/f') > 0 ? $data['rechargeMoney'] = input('rechargeMoney/f') : $this->err('缺少充值金额！');
        input('openid') ? $openid = input('openid') : $this->err('缺少用户openid');

        //查询用户身份
        $user = model('user')->where(['id' => input('cid')])->find();
        if (!$user) {
            $this->err('用户编码错误！');
        }
        $coc = createOrderCode('XB');

        if ($user['userType'] == 1) {//雇主
            $orderId = model('order')->addOrder($coc, 6, $data['cid'], '', $data['rechargeMoney']);
        } else {//阿姨
            $orderId = model('order')->addOrder($coc, 7, '', $data['cid'], $data['rechargeMoney']);
        }

        if ($orderId['status'] == 1) {
            $orderId = $orderId['content'];
        } else {
            $this->err($orderId['msg']);
        }


        //微信支付，发起预支付

        $res = model('pay')->makeWxPreOrder($orderId, $openid);

        $res['status'] ? $this->suc($res['content']) : $this->err($res['msg']);

    }

    /**
     *  赏金提现
     */
    public function pushRewardTake()
    {

        $data = [];
        input('cid') ? $cid = input('cid') : $this->err('缺少用户主键');
        input('takeMoney/d') > 0 ? $data['money'] = input('takeMoney/d') : $this->err('提现金额必须大于零！');
        input('bankNumber') ? $data['bankNumber'] = input('bankNumber') : $this->err('缺少银行卡号！');
        input('bank') ? $data['bank'] = input('bank') : $this->err('缺少银行！');

        input('accountName') ? $data['accountName'] = input('accountName') : $this->err('缺少开户者姓名！');

        input('bankAddress') ? $data['bankAddress'] = input('bankAddress') : $this->err('缺少地址！');


        //启动事务
        Db::startTrans();
        try {
            //查询用户钱包余额
            $res = model('user')->field('id,reward')->where(['id' => $cid])->find();
            $res['reward'] = $res['reward'] - $data['money'];

            if ($res['reward'] < 0) {
                $this->err('提现金额不能大于赏金余额！');
            }

            //查询系统配置提现手续费
            $sy = model('system_config')->field('cashPercent')->where(['status' => 1])->find();
            //手续费
            $cashPercent = $sy['cashPercent'] * $data['money'];
            $data['cid'] = $cid;
            $data['feeAmount'] = $sy['cashPercent'];
            $data['actualAmount'] = $data['money'] - $cashPercent;
            $data['type'] = 2;  //赏金提现
            $data['createTime'] = createTime();

            $l_data = [
                'leftScore' => $res['reward'],
                'score' => $data['money'],
                'createTime' => createTime(),
                'sign' => 2,
                'cid' => $cid,
                'followId' => 0,
                'source' => 6
            ];
            $u_data = [
                'id' => input('cid'),
                'reward' => $res['reward']
            ];
            $cash = model('user_cash')->editData($data);
            $l_res = model('user_reward_log')->editData($l_data);
            $e_rep = model('user')->editData($u_data, $u_data['id']);
            if ($cash) {
                //提交事务
                Db::commit();
                $this->suc('操作成功，等待后台审核！');
            } else {
                Db::rollback();
                $this->err('提现失败！');
            }
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $this->err('操作失败！');
        }
    }

    /**
     *  提现
     */
    public function pushMoneyTake()
    {

        $data = [];
        input('cid') ? $cid = input('cid') : $this->err('缺少用户主键');
        input('takeMoney/d') > 0 ? $data['money'] = input('takeMoney/d') : $this->err('提现金额必须大于零！');
        input('bankNumber') ? $data['bankNumber'] = input('bankNumber') : $this->err('缺少银行卡号！');
        input('bank') ? $data['bank'] = input('bank') : $this->err('缺少银行！');

        input('accountName') ? $data['accountName'] = input('accountName') : $this->err('缺少开户者姓名！');

        input('bankAddress') ? $data['bankAddress'] = input('bankAddress') : $this->err('缺少地址！');


        //启动事务
        Db::startTrans();
        try {
            //查询用户钱包余额
            $res = model('user')->field('id,money')->where(['id' => $cid])->find();
            $res['money'] = $res['money'] - $data['money'];

            if ($res['money'] < 0) {
                $this->err('提现金额不能大于钱包余额！');
            }

            //查询系统配置提现手续费
            $sy = model('system_config')->where(['status' => 1])->find();
            //手续费
            $cashPercent = $sy['cashPercent'] * $data['money'];
            $data['cid'] = $cid;
            $data['feeAmount'] = $sy['cashPercent'];
            $data['actualAmount'] = $data['money'] - $cashPercent;
            $data['type'] = 1;  //钱包提现
            $data['createTime'] = createTime();

            $l_data = [
                'leftMoney' => $res['money'],
                'money' => $data['money'],
                'moneySn' => createOrderCode('ZJ'),
                'createTime' => createTime(),
                'moneyType' => 2,
                'targetId' => $cid,
                'orderSrc' => 3,
                'status' => 2
            ];
            $u_data = [
                'id' => input('cid'),
                'money' => $res['money']
            ];
            $cash = model('user_cash')->editData($data);
            $l_res = model('user_money_log')->editData($l_data);
            $e_rep = model('user')->editData($u_data, $u_data['id']);
            if ($cash) {
                //提交事务
                Db::commit();
                $this->suc('操作成功，等待后台审核！');
            } else {
                Db::rollback();
                $this->err('提现失败！');
            }
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $this->err('操作失败！');
        }
    }

    /**
     *  点亮好阿姨或者雇主
     */
    public function editGoodEmployer()
    {
        $data = [];
        input('cid') ? $data['id'] = input('cid') : $this->err('缺少用户主键');
        input('openid') ? $openid = input('openid') : $this->err('缺少用户openid');
        input('payType') ? $data['payType'] = input('payType') : $this->err('缺少支付方式！');
        input('userCouponId') ? $userCouponId = input('userCouponId') : true;

        $user = model('user')->where(['id' => $data['id']])->find();

        //获取已启用的系统配置
        $sy = model('system_config')->where(['status' => 1])->find();
        if (!$sy) {
            $this->err('获取系统配置错误！');
        }
        //获取点亮费用
        $money = $sy['lightenFee'];

        $user['userType'] == 1 ? $id = $data['id'] : true;
        $user['userType'] == 2 ? $id = $data['id'] : true;

        // 判断是否使用优惠券
        if (input('userCouponId')) {
            $userCouponId = input('userCouponId');
        } else {
            $userCouponId = 0;
        }
        $coc = createOrderCode('XB');
        //1-雇主
        if ($user['userType'] == 1) {
            if ($user['isGoodEmployer'] == 1) {
                $this->err('已经是好雇主！');
            } else {
                $orderId = model('order')->addOrder($coc, 4, $id, '', $money, $userCouponId);

            }
        } else {    // 2-阿姨
            if ($user['isGoodWorker'] == 1) {
                $this->err('已经是好阿姨！');
            } else {
                $orderId = model('order')->addOrder($coc, 5, '', $id, $money, $userCouponId);
            }
        }
        if ($orderId['status'] == 1) {
            $orderId = $orderId['content'];
        } else {
            $this->err($orderId['msg']);
        }

        if ($data['payType'] == 1) {
            Db::startTrans();
            try {
                //钱包支付
                $res = model('pay')->pay($id, $money, 2, 1, 7, $orderId, $userCouponId);

                //查询订单交易金额
                $o_res = model('order')->where(['id' => $orderId])->find();
                //交易成功后增加自己积分
                $points = model('user')->editScore($id, 1, $o_res['totalAmount'], 2, 1, '', $orderId);

                if (!$points) {
                    $this->err('积分增加失败！');
                }
                if ($user['leaderId']) {
                    //查询上级用户的赏金,魅力分
                    $leader = model('user')->field('id,isPartner,reward,charm')->where(['id' => $user['leaderId']])->find();

                    //判断上级用户是不是合伙人
                    if ($leader['isPartner'] == 1) {
                        model('user')->editScore($leader['id'], 1, $o_res['totalAmount'] * $sy['partnerInviteReward'], 3, 3, $id, $orderId);
                    } else {
                        //一级赏金比率
                        if ($leader['charm'] < $sy['secondInviteValue']) {
                            model('user')->editScore($leader['id'], 1, $o_res['totalAmount'] * $sy['firstInviteReward'], 3, 3, $id, $orderId);
                        }
                        //二级赏金比率
                        if ($sy['secondInviteValue'] <= $leader['charm'] && $leader['charm'] < $sy['thirdInviteValue']) {
                            model('user')->editScore($leader['id'], 1, $o_res['totalAmount'] * $sy['secondInviteReward'], 3, 3, $id, $orderId);
                        }
                        //三级赏金比率
                        if ($sy['thirdInviteValue'] <= $leader['charm']) {
                            model('user')->editScore($leader['id'], 1, $o_res['totalAmount'] * $sy['thirdInviteReward'], 3, 3, $id, $orderId);
                        }
                    }
                }
                //交易完成赠送优惠券
                $coupon_count = model('coupon')->where(['couponType' => 1003])->count();
                if ($coupon_count) {
                    $coupon = model('coupon')->getOrderCoupon($data['id']);
                }

                //查询是否申请合伙人
                $status = ['<>',1];   //status 1-审核已通过！
                $apply = model('street_apply')->where(['cid'=>$id,'status'=>$status])->count();
                if($apply){
                    model('street_apply')->where(['cid'=>$id])->update(['status'=>1]);

                    model('user')->where(['id'=>$id])->update(['isPartner'=>1]);
                }

                if ($res['status']) {
                    Db::commit();
                    $res['content'] = $coc;
                    $this->suc($res['content']);
                } else {
                    Db::rollback();
                    $this->err($res['msg']);
                }
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                $this->err('操作失败！');
            }
        }
        //微信支付，发起预支付
        if ($data['payType'] == 2) {
            $res = model('pay')->makeWxPreOrder($orderId, $openid, $userCouponId);
            $content = $res['content'];
            $content['orderSn'] = $coc;
            $res['content'] = $content;
            $res['status'] ? $this->suc($res['content']) : $this->err($res['msg']);
        }

    }

    /**
     *  获取用户优惠券列表
     */
    public function getUserCouponList()
    {
        $where = [];
        input('cid') ? $where['cid'] = input('cid') : $this->err('缺少用户主键！');
        //验证用户编码
        $cid = model('user')->where(['id' => $where['cid']])->count();
        if (!$cid) {
            $this->err('用户编码错误！');
        }
        //1 -未使用的优惠券
        $where['uc.status'] = 1;
        $where['overTime'] = ['> time', time()];
        $res = model('user_coupon')
            ->alias('uc')
            ->field('c.* ,uc.overTime, uc.id as ucId,uc.createTime as userCreateTime')
            ->join('coupon c', 'uc.couponId=c.id', 'left')
            ->where($where)
            ->order('uc.id desc')
            ->paginate()
            ->toArray();

        $res ? $this->suc($res) : $this->err('获取用户优惠券列表失败');
    }

    /**
     *  获取用户钱包日志
     */
    public function getUserMoneyList()

    {
        $where = [];
        input('cid') ? $where['targetId'] = input('cid') : $this->err('缺少用户主键！');
        //验证用户编码
        $cid = model('user')->where(['id' => $where['targetId']])->count();
        if (!$cid) {
            $this->err('用户编码错误！');
        }
        $res = model('user_money_log')
            ->alias('l')
            ->field('l.*,o.type ')
            ->join('order o', 'o.id=l.orderId', 'left')
            ->where(['targetId' => $where['targetId']])
            ->order('l.id desc')
            ->paginate(10)
            ->toArray();

        $res ? $this->suc($res) : $this->err('获取用户钱包日志失败！');

    }

    /**
     *  获取用户赏金日志
     */
    public function getUserRewardList()
    {
        $where = [];
        input('cid') ? $where['cid'] = input('cid') : $this->err('缺少用户主键！');
        //验证用户编码
        $cid = model('user')->where(['id' => $where['cid']])->count();
        if (!$cid) {
            $this->err('用户编码错误！');
        }

        $res = model('user_reward_log')
            ->alias('url')
            ->field('url.*, u.name as userName,us.name as followName')
            ->join('user u', 'u.id = url.cid', 'left')
            ->join('user us', 'us.id = url.followId', 'left')
            ->where($where)
            ->order('url.id desc')
            ->paginate(10)
            ->toArray();
        $res ? $this->suc($res) : $this->err('获取用户赏金日志失败！');

        /* $where = [];
         input('cid') ? $where['cid'] = input('cid') : $this->err('缺少用户主键！');
         //验证用户编码
         $cid = model('user')->where(['id' => $where['cid']])->count();
         if (!$cid) {
             $this->err('用户编码错误！');
         }
         $field='url.id,url.sign,url.cid,url.orderId,url.followId,url.source,url.score,url.leftScore,url.createTime,u.name as userName,us.name as followName,o.type';
         $res = model('user_reward_log')
             ->alias('url')
             ->field($field)
             ->join('user u', 'u.id = url.cid', 'left')
             ->join('user us', 'us.id = url.followId','left')
             ->join('order o','o.id=url.orderId','left')
             ->where($where)
             ->order('url.id desc')
             ->paginate(10)
             ->toArray();
         $res ? $this->suc($res) : $this->err('获取用户赏金日志失败！');*/

    }

    /**
     *  relationType 1-雇佣 2-预约 3-关注
     *  cid 用户编码
     *  userType 1-雇主 2-阿姨
     */
    public function getUserRelationList()
    {

        $where = [];
        input('relationType') ? $relationType = input('relationType') : $this->err('缺少选择类型 ！');
        input('userType') ? $userType = input('userType') : $this->err('缺少用户类型 ！');
        input('cid') ? $cid = input('cid') : $this->err('缺少用户主键 ！');
        if ($userType == 1) {
            $where['employeeId'] = $cid;
        } elseif ($userType == 2) {
            $where['workId'] = $cid;
        } else {
            $this->err('用户类型错误！');
        }

        $field = 'u.openid,u.id as cid,u.userType,u.mobile as user,u.province,u.city,u.district, u.avatar,u.street,u.name as userName,u.job as jobId,u.age,u.workCity,DATE_FORMAT(beginTime, \'%H:%i\') as beginTime,
        DATE_FORMAT(endTime, \'%H:%i\') as endTime, u.workYear,u.workDuty,u.salary,u.rest,
       u.legalRest,u.introduction,u.pictureSrc1,u.pictureSrc2,u.pictureSrc3,u.videoSrc,u.videoPicSrc,u.appearance,u.isOpenFollow,u.isOpenChat,u.isHiddenMobile,uc.status as contractStatus,uc.id as contractId,j.name as jobName,
       uR.isFollow,j.jobSalary,u.mobile,u.isGoodWorker,u.isGoodEmployer';

        $a_field = 'u.openid,u.id as cid,u.userType,u.name as userName,u.avatar,j.only,u.introduction,u.pictureSrc1,u.pictureSrc2,u.pictureSrc3,u.videoSrc,u.videoPicSrc,u.appearance,
        u.isOpenFollow,u.isOpenChat,u.isHiddenMobile,j.name as jobName,ue.ageStart,ue.ageEnd,ue.jobId,ue.province,ue.city,ue.district,ue.street,ue.workCity,ue.beginTime,ue.endTime,ue.workyearStart,ue.workyearEnd,
        ue.workDuty,ue.appearance,ue.salary,ue.rest,ue.legalRest,uR.isHire 
,uR.isFollow,uR.trusteeshipStatus,uR.orderId,j.jobSalary,u.mobile,u.isGoodWorker,u.isGoodEmployer';

        switch ($relationType) {
            case 1:
                if ($userType == 1) {
                    //雇主查阿姨
                    $where['uR.isHire'] = 1;
                    $res = model('user_relation')
                        ->distinct(true)
                        ->alias('uR')
                        ->field($field . ', uR.hireTime as hireTime,uR.trusteeshipStatus,uR.orderId,uc.status as contractStatus,uc.id as contractId')
                        ->join('user u', 'u.id=uR.workId', 'left')
                        ->join('user_contract uc', 'uc.orderId=uR.orderId', 'left')
                        ->join('job j ', 'u.job = j.id', 'left')
                        ->where($where)
                        ->order('uR.id desc')
                        ->paginate(10)
                        ->toArray();

                } else {
                    //阿姨查雇主
                    $where['uR.isHire'] = 1;
                    $res = model('user_relation')
                        ->distinct(true)
                        ->alias('uR')
                        ->field('ue.*,u.name as userName,u.userType,u.avatar,u.mobile,uR.trusteeshipStatus,uR.orderId,j.name as jobName,uR.isFollow,uc.status as contractStatus,uc.id as contractId,
                        u.openid,u.mobile,u.isGoodWorker,u.isGoodEmployer,u.isOpenFollow,u.isOpenChat,u.isHiddenMobile,u.pictureSrc1,u.pictureSrc2,u.pictureSrc3,u.videoSrc,u.videoPicSrc')
                        ->join('user_expect ue', 'uR.employeeId = ue.cid', 'left')
                        ->join('user u', 'u.id = uR.employeeId', 'left')
                        ->join('user_contract uc', 'uc.orderId = uR.orderId', 'left')
                        ->join('job j ', 'ue.jobId = j.id', 'left')
                        ->where($where)
                        ->order('uR.id desc')
                        ->paginate(10)
                        ->toArray();

                    $this->suc($res);
                }
                $res ? $this->suc($res) : $this->err('获取信息失败');
                break;
            case 2:
                if ($userType == 1) {
                    $where['uR.isOrder'] = 1;
                    $res = model('user_relation')
                        ->distinct(true)
                        ->alias('uR')
                        ->field($field . ', uR.orderTime as orderTime,uR.trusteeshipStatus,uR.orderId,uc.status as contractStatus,uc.id as contractId')
                        ->join('user u', 'u.id=uR.workId', 'left')
                        ->join('user_contract uc', 'uc.orderId=uR.orderId', 'left')
                        ->join('job j ', 'u.job = j.id', 'left')
                        ->where($where)
                        ->order('uR.id desc')
                        ->paginate(10)
                        ->toArray();
                } else {
                    $where['uR.isOrder'] = 1;
                    $res = model('user_relation')
                        ->distinct(true)
                        ->alias('uR')
                        ->field('ue.*,u.name as userName,u.userType,u.avatar,u.mobile,uR.trusteeshipStatus,uR.orderId,
                        j.name as jobName,uR.isFollow,uc.status as contractStatus,uc.id as contractId,u.openid,u.isOpenFollow,u.isOpenChat,u.isHiddenMobile,u.mobile,u.isGoodWorker,u.isGoodEmployer,u.pictureSrc1,u.pictureSrc2,u.pictureSrc3,u.videoSrc,u.videoPicSrc')
                        ->join('user_expect ue', 'uR.employeeId=ue.cid')
                        ->join('user u', 'u.id=uR.employeeId', 'left')
                        ->join('user_contract uc', 'uc.orderId=uR.orderId', 'left')
                        ->join('job j ', 'ue.jobId = j.id', 'left')
                        ->where($where)
                        ->order('uR.id desc')
                        ->paginate(10)
                        ->toArray();
                }

                $res ? $this->suc($res) : $this->err('获取信息失败');
                break;
            case 3:
                if (input('userType') == 1) {
                    $res = model('user_relation')
                        ->distinct(true)
                        ->alias('uR')
                        ->field($field . ', uR.followTime as followTime')
                        ->join('user u', 'u.id=uR.workId', 'left')
                        ->join('user_contract uc', 'uc.orderId=uR.orderId', 'left')
                        ->join('job j ', 'u.job = j.id', 'left')
                        ->where($where)
                        ->where(function ($query) {
                            $query->where(['uR.isFollow' => 3])->whereor(['uR.isFollow' => 1]);
                        })
                        ->order('uR.id', 'desc')
                        ->paginate('10')
                        ->toArray();

                    $res ? $this->suc($res) : $this->err('获取信息失败！');
                } else {
                    $res = model('user_relation')
                        ->distinct(true)
                        ->alias('uR')
                        ->field($a_field)
                        ->join('user u', 'u.id=uR.employeeId', 'left')
                        ->join('user_contract uc', 'uc.orderId=uR.orderId', 'left')
                        ->join('user_expect ue', 'ue.cid=uR.employeeId', 'left')
                        ->join('job j ', 'ue.jobId = j.id', 'left')
                        ->where($where)
                        ->where(function ($query) {
                            $query->where(['uR.isFollow' => 3])->whereor(['uR.isFollow' => 2]);
                        })
                        ->order('uR.id', 'desc')
                        ->paginate('10')
                        ->toArray();

                    $res ? $this->suc($res) : $this->err('获取信息失败');
                }
                break;

            default:
                $this->err('用户关系错误！');
                break;

        }
    }

    /**
     *  一键雇佣
     * userType 1-雇主 2 -阿姨
     * only   0唯一岗位 1 不唯一
     */
    public function reservation()
    {
        $data = [];
        input('openid') ? $openid = input('openid') : $this->err('缺少openid');
        input('employeeId') ? $data['employeeId'] = input('employeeId') : $this->err('缺少雇主主键');
        input('workId') ? $data['workId'] = input('workId') : $this->err('缺少阿姨主键');
        input('userType') ? $userType = input('userType') : $this->err('缺少用户类型！');
        input('jobId') ? $jobId = input('jobId') : $this->err('缺少岗位编码！');
        //验证jobId
        $job = model('job')->where(['id' => $jobId])->count();
        if (!$job) {
            $this->err('岗位编码错误！');
        }
        //验证employeeId
        $employeeId = model('user')->where(['id' => $data['employeeId']])->count();
        if (!$employeeId) {
            $this->err('用户编码错误！');
        }
        //验证workId
        $workId = model('user')->where(['id' => $data['workId']])->count();
        if (!$workId) {
            $this->err('用户编码错误！');
        }
        //验证用户类型
        if ($userType != 1 && $userType != 2) {
            $this->err('用户类型错误！');
        }
        //查询是不是唯一岗位
        $job_res = model('job')->where(['id' => $jobId])->find();
        //查看阿姨和雇主是否存在其他关系，有执行编辑无执行新增
        $user_relation = model('user_relation')->where(['employeeId' => $data['employeeId'], 'workId' => $data['workId']])->find();
        //启动事务
        Db::startTrans();
        try {
            if ($job_res['only'] == 0) {  //一键雇佣
                //查询雇主是否有雇佣过的阿姨
                $employeeId_relation = model('user_relation')->where(['employeeId' => $data['employeeId'], 'isHire' => 1])->find();
                $employeeIdWork_relation = model('user_relation')->where(['employeeId' => $data['employeeId'], 'workId' => $data['workId'], 'isHire' => 1])->find();
                //查询阿姨是否已有雇主
                //    $work_relation = model('user_relation')->where(['workId' => $data['workId'],'isHire' => 1])->find();
                //雇主雇佣阿姨
                if ($userType == 1) {
                    $employeeIdWork_relation ? $this->err('该用户已雇佣，请到我的阿姨里先解除关系！') : true;
                    $employeeId_relation ? $this->err('您已有雇佣的阿姨，请到我的阿姨里先解除关系！') : true;
                    //    $work_relation ? $this->err('该阿姨已有雇主，请选择其他阿姨！') : true;
                } else {
                    $work_relation = model('user_relation')->where(['workId' => $data['workId'], 'employeeId' => $data['employeeId'], 'isHire' => 1])->find();
                    $work_relation ? $this->err('该用户已雇佣，请到我的雇主里先解除关系！') : true;
                    /* $employeeId_relation = model('user_relation')->where(['employeeId' => $data['employeeId'],'workId' => $data['workId'],'isOrder' => 1])->find();
                     $employeeId_relation ? $this->err('该用户已预约，请到我的预约里先解出关系！') : true;*/
                }

                if ($user_relation) {
                    //阿姨和雇主存在其他关系执行编辑操作
                    $res = model('user_relation')->where(['employeeId' => $data['employeeId'], 'workId' => $data['workId']])->update(['isHire' => 1]);
                } else {
                    //阿姨和雇主存无任何关系执行新增操作
                    $data['hireTime'] = createTime();
                    $data['isHire'] = 1;
                    $data['createTime'] = createTime();
                    $res = model('user_relation')->editData($data);
                }
            } else { //一键预约
                if ($user_relation) {
                    //阿姨和雇主存在其他关系执行编辑操作
                    $res = model('user_relation')->where(['employeeId' => $data['employeeId'], 'workId' => $data['workId']])->update(['isOrder' => 1]);
                } else {
                    //阿姨和雇主存无任何关系执行新增操作
                    $data['orderTime'] = createTime();
                    $data['isOrder'] = 1;
                    $data['createTime'] = createTime();
                    $res = model('user_relation')->editData($data);
                }
            }

            $employee_data = [
                'cid' => $data['employeeId'],
                'isHire' => 1
            ];

            model('user_expect')->where(['cid' => $data['employeeId']])->update($employee_data);

            if ($res) {
                //提交事务
                Db::commit();
                $this->suc($job_res['only']);
            } else {
                //回滚事务
                Db::rollback();
                $this->err('该用户已预约，请到我的预约里面解除关系！');
            }

        } catch (\Exception $e) {
            //回滚事务
            Db::rollback();
            $this->err('操作失败！');
        }

    }

    /**
     * 托管工资
     */
    public function trusteeshipWages()
    {

        input('openid') ? $openid = input('openid') : $this->err('缺少openid');
        input('employeeId') ? $data['employeeId'] = input('employeeId') : $this->err('缺少雇主主键');
        input('workId') ? $data['workId'] = input('workId') : $this->err('缺少阿姨主键');
        input('userType') ? $data['userType'] = input('userType') : $this->err('缺少用户类型！');
        input('payType') ? $data['payType'] = input('payType') : $this->err('缺少支付类型！');
        input('salary') ? $salary = input('salary') : $this->err('缺少工资！');

        $user = model('user')->where(['openid' => $openid])->find();
        //验证是否已托管工资
        $trusteeshipStatus = model('user_relation')->where(['employeeId' => $data['employeeId'], 'workId' => $data['workId']])->find();
        if ($trusteeshipStatus['trusteeshipStatus'] == 1) {
            $this->err('已经托管过工资了！');
        }
        $data['userType'] == 1 ? $cid = input('employeeId') : true;
        $data['userType'] == 2 ? $cid = input('workId') : true;

        //订单编码
        $coc = createOrderCode('XB');
        //添加订单
        $order_data = [
            'orderSn' => $coc,
            'type' => 1,
            'employeeId' => $data['employeeId'],
            'workId' => $data['workId'],
            'province' => $user['province'],
            'city' => $user['city'],
            'district' => $user['district'],
            'orderAmount' => $salary,
            'payType' => $data['payType'],
            'createTime' => createTime()
        ];
        $order = model('order')->editData($order_data);
        $order ? true : $this->err('创建订单失败！');

        $order_res = model('order')->where(['orderSn ' => $coc])->find();

        if ($data['payType'] == 1) {
            $res = model('pay')->pay($cid, $salary, 2, 1, 1, $order_res['id']);

            //查询订单交易金额
            $o_res = model('order')->where(['id' => $order_res['id']])->find();
            //工资结算时间
            $now = time();
            $settlementTime = 30 * 86400;
            $settlementTime = date('Y-m-d H;i:s', $now + $settlementTime);

            //交易成功后增加自己积分
            $points = model('user')->editScore($cid, 1, $o_res['orderAmount'], 2, 1);
            if (!$points) {
                $this->err('积分增加失败！');
            }
            $user = model('user')->field('leaderId')->where(['id' => $cid])->find();
            if ($user['leaderId']) {
                //查询上级用户的赏金,魅力分
                $leader = model('user')->field('id,isPartner,reward,charm')->where(['id' => $user['leaderId']])->find();
                //获取已启用的系统配置
                $sy = model('system_config')->where(['status' => 1])->find();

                if ($leader['isPartner'] == 1) {
                    model('user')->editScore($leader['id'], 1, $o_res['orderAmount'] * $sy['partnerInviteReward'], 3, 1, $cid);
                } else {
                    //一级赏金比率
                    if ($leader['charm'] < $sy['secondInviteValue']) {
                        model('user')->editScore($leader['id'], 1, $o_res['orderAmount'] * $sy['firstInviteReward'], 3, 1, $cid);
                    }
                    //二级赏金比率
                    if ($sy['secondInviteValue'] <= $leader['charm'] && $leader['charm'] < $sy['thirdInviteValue']) {
                        model('user')->editScore($leader['id'], 1, $o_res['orderAmount'] * $sy['secondInviteReward'], 3, 1, $cid);
                    }
                    //三级赏金比率
                    if ($sy['thirdInviteValue'] <= $leader['charm']) {
                        model('user')->editScore($leader['id'], 1, $o_res['orderAmount'] * $sy['thirdInviteReward'], 3, 1, $cid);
                    }
                }
            }
            if ($res['status'] == 1) {
                model('user_relation')
                    ->where(['employeeId' => $data['employeeId'], 'workId' => $data['workId']])
                    ->update(['managedWages' => $o_res['orderAmount'], 'settlementTime' => $settlementTime, 'trusteeshipStatus' => 1, 'orderId' => $order_res['id']]);
            }
        }
        if ($data['payType'] == 2) {
            $res = model('pay')->makeWxPreOrder($order_res['id'], $openid);
        }

        $res['status'] ? $this->suc($res['content']) : $this->err($res['msg']);

    }

    /**
     *  开通vip
     */
    public function openVip()
    {
        $where = [];
        $data = [];
        $m_user = model('user');
        input('cid') ? $where['cid'] = input('cid') : $this->err('缺少用户主键！');
        input('openid') ? $openid = input('openid') : $this->err('缺少openid');
        input('payType') ? $data['payType'] = input('payType') : $this->err('缺少支付类型！');
        input('userCouponId') ? $data['userCouponId'] = input('userCouponId') : true;
        //分享者id
        input('shareId') ? $shareId = input('shareId') : true;

        input('category') ? $type = input('category') : $this->err('缺少选择类型！');

        //获取已启用的系统配置
        $sy = model('system_config')->where(['status' => 1])->find();
        if (!$sy) {
            $this->err('系统配置错误！');
        }

        if($type==1){ //开通月卡

            //获得月卡金额
            $vipMoney = $sy['vipMoney'];

            //订单编码
            $coc = createOrderCode('XB');

            // 判断是否使用优惠券
            if (input('userCouponId')) {
                $userCouponId = input('userCouponId');
            } else {
                $userCouponId = 0;
            }

            //查询用户类型
            $user = $m_user->where(['id' => $where['cid']])->find();

            if (!empty($shareId)) {
                if ($user['userType'] == 1) {
                    $order = model('order')->addOrder($coc, 2, $where['cid'], '', $vipMoney, $userCouponId, $shareId);
                } else {
                    $order = model('order')->addOrder($coc, 3, '', $where['cid'], $vipMoney, $userCouponId, $shareId);
                }
                $order ? true : $this->err('创建订单失败！');
            } else {
                if ($user['userType'] == 1) {
                    $order = model('order')->addOrder($coc, 2, $where['cid'], '', $vipMoney, $userCouponId);
                } else {
                    $order = model('order')->addOrder($coc, 3, '', $where['cid'], $vipMoney, $userCouponId);
                }
                $order ? true : $this->err('创建订单失败！');
            }

            //获取订单id
            if ($order['status'] == 1) {
                $orderId = $order['content'];
            } else {
                $this->err($order['msg']);
            }
            //选择支付方式 1-钱包支付 2-微信支付

            if ($data['payType'] == 1) { //钱包支付
                Db::startTrans();
                try {
                    $res = model('pay')->pay($where['cid'], $vipMoney, 2, 1, 2, $orderId, $userCouponId);

                    if (!$res['status']) {
                        Db::rollback();
                        $this->err($res['msg']);
                    }
                    //根据订单id查询订单信息
                    $orderMoney = model('order')->where(['id' => $orderId])->find();
                    //交易成功后增加自己积分
                    $points = model('user')->editScore(input('cid'), 1, $orderMoney['totalAmount'], 2, 1, '', $orderId);
                    //判断是否有上级用户
                    if ($user['leaderId']) {
                        //查询上级用户的赏金,魅力分
                        $leader = model('user')->where(['id' => $user['leaderId']])->find();


                        //判断是否合伙人
                        if ($leader['isPartner'] == 1) {

                            $reward = model('user')->editScore($leader['id'], 1, $orderMoney['totalAmount'] * $sy['partnerInviteReward'], 3, 1, input('cid'), $orderId);
                        } else {
                            //一级赏金比率
                            if ($leader['charm'] < $sy['secondInviteValue']) {

                                $reward = model('user')->editScore($leader['id'], 1, $orderMoney['totalAmount'] * $sy['firstInviteReward'], 3, 1, input('cid'), $orderId);
                            }
                            //二级赏金比率
                            if ($sy['secondInviteValue'] <= $leader['charm'] && $leader['charm'] < $sy['thirdInviteValue']) {
                                $reward = model('user')->editScore($leader['id'], 1, $orderMoney['totalAmount'] * $sy['secondInviteReward'], 3, 1, input('cid'), $orderId);
                            }
                            //三级赏金比率
                            if ($sy['thirdInviteValue'] <= $leader['charm']) {
                                $reward = model('user')->editScore($leader['id'], 1, $orderMoney['totalAmount'] * $sy['thirdInviteReward'], 3, 1, input('cid'), $orderId);
                            }
                        }
                    }

                    if (!empty($shareId)) {
                        $shareUser = $m_user->where(['id' => $shareId])->find();
                        if ($shareUser) {
                            if ($shareId == $where['cid']) {
                                $this->err('禁止分享给自己！');
                            }
                            //查询分享者信息
                            $reward = $m_user->editScore($shareId, 1, $orderMoney['totalAmount'] * $sy['shareReward'], 3, 4, input('cid'), $orderId);

                        }
                    }
                    //下单赠送优惠券
                    $coupon_count = model('coupon')->where(['couponType' => 1003])->count();
                    if ($coupon_count) {
                        $coupon = model('coupon')->getOrderCoupon($where['cid']);
                    }

                    //查询是否申请合伙人
                    $status = ['<>',1];   //status 1-审核已通过！
                    $apply = model('street_apply')->where(['cid'=>$where['cid'],'status'=>$status])->count();
                    if($apply){
                        model('street_apply')->where(['cid'=>$where['cid']])->update(['status'=>1]);

                        model('user')->where(['id'=>$where['cid']])->update(['isPartner'=>1]);
                    }

                    Db::commit();
                    $res['content'] = $coc;
                    $this->suc($coc);
                } catch (\Exception $e) {
                    // 回滚事务
                    Db::rollback();
                    $this->err('操作失败！');
                }
            }
            if ($data['payType'] == 2) {
                $res = model('pay')->makeWxPreOrder($orderId, $openid, $userCouponId);

                $content = $res['content'];
                $content['orderSn'] = $coc;
                $res['content'] = $content;
                $res['status'] ? $this->suc($res['content']) : $this->err($res['msg']);
            }
        }elseif($type==2){ //开通年卡

            //获得年卡金额
            $vipMoney = $sy['yearVip'];

            //订单编码
            $coc = createOrderCode('XB');

            // 判断是否使用优惠券
            if (input('userCouponId')) {
                $userCouponId = input('userCouponId');
            } else {
                $userCouponId = 0;
            }

            //查询用户类型
            $user = $m_user->where(['id' => $where['cid']])->find();

            if (!empty($shareId)) {
                if ($user['userType'] == 1) {
                    $order = model('order')->addOrder($coc, 8, $where['cid'], '', $vipMoney, $userCouponId, $shareId);
                } else {
                    $order = model('order')->addOrder($coc, 9, '', $where['cid'], $vipMoney, $userCouponId, $shareId);
                }
                $order ? true : $this->err('创建订单失败！');
            } else {
                if ($user['userType'] == 1) {
                    $order = model('order')->addOrder($coc, 8, $where['cid'], '', $vipMoney, $userCouponId);
                } else {
                    $order = model('order')->addOrder($coc, 9, '', $where['cid'], $vipMoney, $userCouponId);
                }
                $order ? true : $this->err('创建订单失败！');
            }

            //获取订单id
            if ($order['status'] == 1) {
                $orderId = $order['content'];
            } else {
                $this->err($order['msg']);
            }
            //选择支付方式 1-钱包支付 2-微信支付

            if ($data['payType'] == 1) { //钱包支付
                Db::startTrans();
                try {
                    $res = model('pay')->pay($where['cid'], $vipMoney, 2, 1, 8, $orderId, $userCouponId);

                    if (!$res['status']) {
                        Db::rollback();
                        $this->err($res['msg']);
                    }
                    //根据订单id查询订单信息
                    $orderMoney = model('order')->where(['id' => $orderId])->find();
                    //交易成功后增加自己积分
                    $points = model('user')->editScore(input('cid'), 1, $orderMoney['totalAmount'], 2, 1, '', $orderId);
                    //判断是否有上级用户
                    if ($user['leaderId']) {
                        //查询上级用户的赏金,魅力分
                        $leader = model('user')->where(['id' => $user['leaderId']])->find();


                        //判断是否合伙人
                        if ($leader['isPartner'] == 1) {

                            $reward = model('user')->editScore($leader['id'], 1, $orderMoney['totalAmount'] * $sy['partnerInviteReward'], 3, 1, input('cid'), $orderId);
                        } else {
                            //一级赏金比率
                            if ($leader['charm'] < $sy['secondInviteValue']) {

                                $reward = model('user')->editScore($leader['id'], 1, $orderMoney['totalAmount'] * $sy['firstInviteReward'], 3, 1, input('cid'), $orderId);
                            }
                            //二级赏金比率
                            if ($sy['secondInviteValue'] <= $leader['charm'] && $leader['charm'] < $sy['thirdInviteValue']) {
                                $reward = model('user')->editScore($leader['id'], 1, $orderMoney['totalAmount'] * $sy['secondInviteReward'], 3, 1, input('cid'), $orderId);
                            }
                            //三级赏金比率
                            if ($sy['thirdInviteValue'] <= $leader['charm']) {
                                $reward = model('user')->editScore($leader['id'], 1, $orderMoney['totalAmount'] * $sy['thirdInviteReward'], 3, 1, input('cid'), $orderId);
                            }
                        }
                    }

                    if (!empty($shareId)) {
                        $shareUser = $m_user->where(['id' => $shareId])->find();
                        if ($shareUser) {
                            if ($shareId == $where['cid']) {
                                $this->err('禁止分享给自己！');
                            }
                            //查询分享者信息
                            $reward = $m_user->editScore($shareId, 1, $orderMoney['totalAmount'] * $sy['shareReward'], 3, 4, input('cid'), $orderId);

                        }
                    }
                    //下单赠送优惠券
                    $coupon_count = model('coupon')->where(['couponType' => 1003])->count();
                    if ($coupon_count) {
                        $coupon = model('coupon')->getOrderCoupon($where['cid']);
                    }

                    //查询是否申请合伙人
                    $status = ['<>',1];   //status 1-审核已通过！
                    $apply = model('street_apply')->where(['cid'=>$where['cid'],'status'=>$status])->count();
                    if($apply){
                        model('street_apply')->where(['cid'=>$where['cid']])->update(['status'=>1]);

                        model('user')->where(['id'=>$where['cid']])->update(['isPartner'=>1]);
                    }

                    Db::commit();
                    $res['content'] = $coc;
                    $this->suc($coc);
                } catch (\Exception $e) {
                    // 回滚事务
                    Db::rollback();
                    $this->err('操作失败！');
                }
            }
            if ($data['payType'] == 2) {
                $res = model('pay')->makeWxPreOrder($orderId, $openid, $userCouponId);

                $content = $res['content'];
                $content['orderSn'] = $coc;
                $res['content'] = $content;
                $res['status'] ? $this->suc($res['content']) : $this->err($res['msg']);
            }

        }




    }

    /**
     *  搜索
     */
    public function search()

    {
        input('cid') ? $cid = input('cid') : $this->err('缺少用户主键！');
        input('searchContent') ? $data['searchContent'] = input('searchContent') : true;
        input('city') ? $city = input('city') : true;

        $field = 'u.openid,u.id as cid,u.userType,u.province,u.city,u.district, u.avatar,u.street,u.name,u.job as jobId,u.age,u.workCity,DATE_FORMAT(beginTime, \'%H:%i\') as beginTime ,
        DATE_FORMAT(endTime, \'%H:%i\') as endTime, u.workYear,u.workDuty,u.salary,u.rest,j.only,
        u.legalRest,u.introduction,u.pictureSrc1,u.pictureSrc2,u.pictureSrc3,u.videoSrc,u.videoPicSrc,u.appearance,u.isOpenFollow,u.isOpenChat,u.isHiddenMobile,j.name as jobName,
        ur2.isFollow,j.jobSalary,u.maxSalary,u.minSalary,u.isGoodWorker,u.isGoodEmployer';

        $a_field = 'u.openid,u.id as cid,u.userType,u.name,u.avatar,j.only,u.introduction,u.pictureSrc1,u.pictureSrc2,u.pictureSrc3,u.videoSrc,u.videoPicSrc,u.appearance,
        u.isOpenFollow,u.isOpenChat,u.isHiddenMobile,j.name as jobName,ue.ageStart,ue.ageEnd,ue.jobId,ue.province,ue.city,ue.district,ue.street,ue.workCity,ue.beginTime,ue.endTime,
        ue.workyearStart,ue.workyearEnd,ue.workDuty,ue.appearance,ue.salary,ue.rest,ue.legalRest,ur2.isFollow,j.jobSalary,ue.maxSalary,ue.minSalary,u.isGoodWorker,u.isGoodEmployer';

        $user_res = model('user')->where(['id' => $cid])->find();

        $user = model('user_expect')->where(['cid' => $cid])->find();

        if ($user_res['isPushExpect'] == 0 && empty($data['searchContent'])) {
            $this->suc();
        }

        //雇主查询阿姨条件
        $where = [
            'u.userStatus' => 1,
            'u.userType' => 2,
            'u.isPushExpect' => 1,
            'u.city' => $user_res['city'],
        ];
        //阿姨查询雇主条件
        $a_where = [
            'u.userStatus' => 1,
            'u.userType' => 1,
            'u.isPushExpect' => 1,
            'ue.city' => $user_res['city'],
        ];

        if (input('city')) {
            $where['u.city'] = input('city');
            $a_where['ue.city'] = input('city');
        }

        //如果没有输入内容，系统根据用户发布的需求匹配
        if (empty($data['searchContent'])) {
            if ($user_res['userType'] == 1) {
                $where['u.workDuty'] = $user['workDuty'];
                $where['u.age'] = ['between', [$user['ageStart'] - 2, $user['ageEnd'] + 2]];
                //雇主到用户表查阿姨
                $res = model('user')
                    ->alias('u')
                    ->field($field)
                    ->join('job j ', 'j.id = u.job', 'left')
                    ->join('user_relation ur2', 'u.id = ur2.workId and ' . $cid . ' = ur2.employeeId', 'left')
                    ->where($where)
                    ->order('u.id desc')
                    ->paginate(10)
                    ->toArray();

            } else {

                $a_where['ue.workDuty'] = $user_res['workDuty'];
                $a_where['ue.ageStart'] = ['>=', $user_res['age'] - 2];
                $a_where['ue.ageEnd'] = ['<=', $user_res['age'] + 2];
                //阿姨到需求表查雇主
                $res = model('user_expect')
                    ->alias('ue')
                    ->field($a_field)
                    ->join('job j', 'j.id=ue.jobId', 'left')
                    ->join('user u', 'u.id = ue.cid', 'left')
                    ->join('user_relation ur2', 'ue.cid = ur2.employeeId and ' . $cid . ' = ur2.workId', 'left')
                    ->where($a_where)
                    ->order('ue.id desc')
                    ->paginate(10)
                    ->toArray();
            }
        } else {
            /*
                        //雇主到用户表查阿姨
                        if ($user_res['userType'] == 1) {
                            //判断输入数据类型
                            if (is_numeric($data['searchContent'])) {
                                $where['u.age'] = ['between', [$data['searchContent'] - 2, $data['searchContent'] + 2]];
                            } else {
                                $where['u.workDuty'] = ['like', '%' . input('searchContent') . '%'];
                            }

                            $res = model('user')
                                ->alias('u')
                                ->field($field)
                                ->join('job j ', 'j.id = u.job', 'left')
                                ->join('user_relation ur2', 'u.id = ur2.workId and ' . $cid . ' = ur2.employeeId', 'left')
                                ->where($where)
                                ->order('u.id desc')
                                ->paginate(10)
                                ->toArray();

                        } else {

                            //判断输入数据类型
                            if (is_numeric($data['searchContent'])) {
                                $a_where['ue.ageStart'] = ['<=', $data['searchContent']];
                                $a_where['ue.ageEnd'] = ['>=', $data['searchContent']];
                            } else {
                                $a_where['ue.workDuty'] = ['like', '%' . input('searchContent') . '%'];
                            }

                            $res = model('user_expect')
                                ->alias('ue')
                                ->field($a_field)
                                ->join('job j', 'j.id=ue.jobId', 'left')
                                ->join('user u', 'u.id = ue.cid', 'left')
                                ->join('user_relation ur2', 'ue.cid = ur2.employeeId and ' . $cid . ' = ur2.workId', 'left')
                                ->order('ue.id desc')
                                ->paginate(10)
                                ->toArray();

                        }*/

            //雇主到用户表查阿姨
            if ($user_res['userType'] == 1) {
                //判断输入数据类型

                $res = model('user')
                    ->alias('u')
                    ->field($field)
                    ->join('job j ', 'j.id = u.job', 'left')
                    ->join('user_relation ur2', 'u.id = ur2.workId and ' . $cid . ' = ur2.employeeId', 'left')
                    ->where($where)
                    ->where(function ($query) {
                        $query->where(['u.age' => ['between', [input('searchContent') - 2, input('searchContent') + 2]]])
                            ->whereor(['u.workDuty' => ['like', '%' . input('searchContent') . '%']])
                            ->whereor(['u.name' => ['like', '%' . input('searchContent') . '%']])
                            ->whereor(['j.name' => ['like', '%' . input('searchContent') . '%']]);
                    })
                    ->order('u.id desc')
                    ->paginate(10)
                    ->toArray();

            } else {
                $res = model('user_expect')
                    ->alias('ue')
                    ->field($a_field)
                    ->join('job j', 'j.id=ue.jobId', 'left')
                    ->join('user u', 'u.id = ue.cid', 'left')
                    ->join('user_relation ur2', 'ue.cid = ur2.employeeId and ' . $cid . ' = ur2.workId', 'left')
                    ->where($a_where)
                    ->where(function ($query) {
                        $query->where(['ue.ageStart' => ['<=', input('searchContent')]])
                            ->where(['ue.ageEnd' => ['>=', input('searchContent')]])
                            ->whereor(['ue.workDuty' => ['like', '%' . input('searchContent') . '%']])
                            ->whereor(['j.name' => ['like', '%' . input('searchContent') . '%']])
                            ->whereor(['u.name' => ['like', '%' . input('searchContent') . '%']]);
                    })
                    ->order('ue.id desc')
                    ->paginate(10)
                    ->toArray();

            }

        }

        $res ? $this->suc($res) : $this->err('没有搜到查询结果！');

    }

    /**
     *  附近的人
     */
    public function queryPeople()
    {
        $where = [];
        $data = [];
        $a_where = [];
        $res = 0;
        input('cid') ? $cid = input('cid') : $this->err('缺少用户主键！');
        input('latitude') ? $data['$lat1'] = input('latitude') : $this->err('缺少纬度！');
        input('longitude') ? $data['$lng1'] = input('longitude') : $this->err('缺少经度！');
        input('userType') ? $where['userType'] = input('userType') : $this->err('缺少用户类型！');
        // 查询30公里内的用户
        $getDistance = calcScope($data['$lat1'], $data['$lng1'], 30000);

        $where['u.latitude'] = ['between', [$getDistance['minLat'], $getDistance['maxLat']]];
        $where['u.longitude'] = ['between', [$getDistance['minLng'], $getDistance['maxLng']]];
        $where['u.id'] = ['<>', $cid];


        $a_where['u.latitude'] = ['between', [$getDistance['minLat'], $getDistance['maxLat']]];
        $a_where['u.longitude'] = ['between', [$getDistance['minLng'], $getDistance['maxLng']]];
        $a_where['u.id'] = ['<>', $cid];

        $field = ['u.id', 'u.name', 'u.avatar', 'u.userType', 'u.job as jobId', 'u.workDuty', 'u.district', 'u.street', 'u.latitude', 'u.longitude', 'j.name as jobName', 'u.isPushExpect', 'u.maxSalary', 'u.minSalary'];
        $a_field = ['u.id', 'u.name', 'u.avatar', 'u.userType', 'ue.jobId', 'ue.workDuty', 'ue.district', 'ue.street', 'j.name as jobName', 'u.latitude', 'u.longitude,u.isPushExpect,ue.maxSalary,ue.minSalary'];

        // 计算距离， 参数说明：6378.137 地球赤道半径，3.1415926535898 圆周率
        $distance_field = "(2 * 6378.137* ASIN(SQRT(POW(SIN(3.1415926535898*(" . $data['$lat1'] . "-latitude)/360),2)+COS(3.1415926535898*"
            . $data['$lat1'] . "/180)* COS(latitude * 3.1415926535898/180)*POW(SIN(3.1415926535898*(" . $data['$lng1'] . "-longitude)/360),2))))*1000 as distance";
        array_push($field, $distance_field);
        array_push($a_field, $distance_field);
        if (input('userType') == 1) {
            $where['userType'] = 2;

            //雇主查阿姨
            $res = model('user')
                ->alias('u')
                ->field($field)
                ->join('job j', 'u.job = j.id', 'left')
                ->where($where)
                ->order("distance")
                ->paginate(10)
                ->toArray();
        } elseif (input('userType') == 2) {
            $a_where['u.userType'] = 1;
            $res = model('user_expect')
                ->alias('ue')
                ->field($a_field)
                ->join('user u', 'ue.cid = u.id', 'left')
                ->join('job j', 'ue.jobId = j.id', 'left')
                ->where($a_where)
                ->order("distance")
                ->paginate(10)
                ->toArray();

        } else {
            $this->err('用户类型不正确！');
        }

        $res ? $this->suc($res) : $this->err('失败！');

    }

    /**
     * 附近的人详情
     */
    public function queryPeopleDetail()
    {
        $where = [];
        //他人的主键
        input('employeeId') ? $where['employeeId'] = input('employeeId') : $this->err('缺少用户编码！');
        input('workId') ? $where['workId'] = input('workId') : $this->err('缺少用户编码！');
        input('userType') ? $userType = input('userType') : $this->err('缺少用户类型！');

        $employee_distance = model('user')->where(['id' => $where['employeeId']])->find();
        $work_distance = model('user')->where(['id' => $where['workId']])->find();

        $distance = getDistance($employee_distance['latitude'], $employee_distance['longitude'], $work_distance['latitude'], $work_distance['longitude']);
        $field = 'u.openid,u.id as cid,u.userType,u.province,u.city,u.district, u.avatar,u.street,u.name as userName,u.job as jobId,u.age,u.workCity,DATE_FORMAT(beginTime, \'%H:%i\') as beginTime ,
        DATE_FORMAT(endTime, \'%H:%i\') as endTime, u.workYear,u.workDuty,u.salary,u.rest,j.only,
        u.legalRest,u.introduction,u.pictureSrc1,u.pictureSrc2,u.pictureSrc3,u.videoSrc,u.videoPicSrc,u.appearance,u.isOpenFollow,u.isOpenChat,u.isHiddenMobile,j.name as jobName,u.latitude,u.longitude,ur.isHire,ur.isFollow,
        u.maxSalary,u.minSalary,u.isGoodWorker,u.isGoodEmployer
       ';
        $a_field = 'u.openid,u.id as cid,u.userType,u.name as userName,u.avatar,j.only,u.introduction,u.pictureSrc1,u.pictureSrc2,u.pictureSrc3,u.videoSrc,u.videoPicSrc,u.appearance,
        u.isOpenFollow,u.isOpenChat,u.isHiddenMobile,j.name as jobName,ue.ageStart,ue.ageEnd,ue.jobId,ue.province,ue.city,ue.district,ue.street,ue.workCity,ue.beginTime,ue.endTime,ue.workyearStart,ue.workyearEnd,
        ue.workDuty,ue.appearance,ue.salary,ue.rest,ue.legalRest, ur.isHire,u.latitude,u.longitude
,ur.isFollow,ue.maxSalary,ue.minSalary,u.isGoodWorker,u.isGoodEmployer';

        if ($userType == 1) {
            $res = model('user')
                ->alias('u')
                ->field($field)
                ->join('user_relation ur', 'ur.workId=u.id and ' . $where['employeeId'] . ' = ur.employeeId ', 'left')
                ->join('job j', 'j.id=u.job', 'left')
                ->where(['u.id' => $where['workId']])
                ->find();
        } else {
            $res = model('user_expect')
                ->alias('ue')
                ->field($a_field)
                ->join('user_relation ur', 'ur.employeeId=ue.cid and ' . $where['workId'] . ' = ur.workId ', 'left')
                ->join('user u', 'u.id=ue.cid', 'left')
                ->join('job j', 'j.id=ue.jobId', 'left')
                ->where(['ue.cid' => $where['employeeId']])
                ->find();
        }
        $res['distance'] = (int)$distance;
        $res ? $this->suc($res) : $this->err('失败！');
    }

    /**
     *  更新自身位置
     */
    public function updateLocation()
    {

        $data = [];
        input('cid') ? $data['id'] = input('cid') : $this->err('缺少用户主键！');
        input('latitude') ? $data['latitude'] = (float)input('latitude') : $this->err('缺少纬度！');
        input('longitude') ? $data['longitude'] = (float)input('longitude') : $this->err('缺少经度！');
        input('avatar') ? $data['avatar'] = input('avatar') : true;


        // 启动事务
        Db::startTrans();
        try {
            $position = model('user')->getUserPosition($data['latitude'], $data['longitude']);
            $position = $position['content'];
            $position = $position['addressComponent'];

            $position_data['province'] = $position['province'];
            $position_data['city'] = $position['city'];
            $position_data['district'] = $position['district'];
            $position_data['street'] = $position['street'];


            $user = model('user')->where(['id' => $data['id']])->find();
            $user['province'] = $position_data['province'];
            $user['city'] = $position_data['city'];
            $user['district'] = $position_data['district'];
//            $user['street'] = $position_data['street'];
            $res = model('user')->editData($data, $data['id']);
            // 提交事务
            if ($res) {
                Db::commit();
                $this->suc($user);
            } else {
                $this->err('更新失败！');
            }
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $this->err('操作失败！');
        }
    }

    /**
     *  上传视频
     */
    public function uploadVideo()
    {
        $data = [];

        input('cid') ? $data['id'] = input('cid') : $this->err('缺少用户主键！');
        input('pictureSrc1') ? $data['pictureSrc1'] = input('pictureSrc1') : $this->err('缺少图片！');
        input('pictureSrc2') ? $data['pictureSrc2'] = input('pictureSrc2') : true;
        input('pictureSrc3') ? $data['pictureSrc3'] = input('pictureSrc3') : true;
        input('video') ? $data['videoSrc'] = input('video') : $this->err('缺少视频！');
        $data['videoPicSrc'] = $data['videoSrc'] . '?vframe/jpg/offset/5/w/640/h/360';
        $res = model('user')->editData($data, $data['id']);
        $res ? $this->suc($res) : $this->err('上传失败！');

    }

    /**
     *  刷脸登记
     */
    public function uploadIDCard()
    {
        $where = [];
        $data = [];
        input('cid') ? $where['id'] = input('cid') : $this->err('缺少用户主键！');
        input('IDcardPic') ? $data['IDcardPic'] = input('IDcardPic') : $this->err('缺少身份证正面照！');
        input('IDcardPic2') ? $data['IDcardPic2'] = input('IDcardPic2') : $this->err('缺少身份证反面照！');
        input('userPic') ? $data['userPic'] = input('userPic') : $this->err('缺少人物头像！');
        $user = model('user')->where($where)->find();
        if (!$user) {
            $this->err('用户主键错误！');
        }
        if ($user['isFaced'] == 1) {
            $this->err('已经刷脸登记过！');
        }
        if ($user['isFaced'] == 2) {
            $this->err('正在审核中！');
        }
        $data['id'] = input('cid');
        $data['isFaced'] = 2;
        $res = model('user')->editData($data, $data['id']);
        $res ? $this->suc('操作成功！') : $this->err('操作失败！');

    }

    /**
     * 添加语音
     */
    public function voice()
    {
        $data = [];

        input('cid') ? $data['id'] = input('cid') : $this->err('用户主键！');
        input('voice') ? $data['voice'] = input('voice') : $this->err('缺少订单主键！');

        $res = model('user')->editData($data, $data['id']);
        $res ? $this->suc($res) : $this->err('添加语音失败！');

    }

    /**
     * 安全培训
     */
    public function trainingVideo()
    {

        $data = [];
        $where = [];
        input('cid') ? $where['id'] = input('cid') : $this->err('缺少用户主键！');

        //查询用户是否已经安全培训过
        $user = model('user')->field('charm,safed')->where($where)->find();
        if ($user['safed'] == 1) {
            $this->err('该用户已经安全培训过！');
        }
        $data['id'] = input('cid');
        $data['safed'] = 1;
        $sy = model('system_config')->where(['status' => 1])->find();
        $sy ? true : $this->err('查询系统配置失败！');
        $data['charm'] = $sy['safeValue'] + $user['charm'];

        $uc_data = [
            'safeExamPercent' => 1,
            'safePoints' => $sy['safeValue'],
            'cid' => $where['id']
        ];

        //魅力值日志
        $log_data = [
            'sign' => 1,
            'cid' => $where['id'],
            'source' => 6,
            'score' => $sy['safeValue'],
            'leftScore' => $user['charm'] + $sy['safeValue']
        ];
        Db::startTrans();
        //启动数据库事务
        try {
            $res = model('user')->editData($data, $data['id']);

            $user_charm = model('user_charm')->where(['cid' => $where['id']])->count();
            if (!$user_charm) {
                $uc_res = model('user_charm')->editData($uc_data);
            } else {
                $uc_res = model('user_charm')->where(['cid' => $where['id']])->update($uc_data);
            }
            $uc_res ? true : $this->err('更新用户魅力表失败！');
            $l = model('user_charm_log')->editData($log_data);
            $l ? true : $this->err('新增魅力值日志失败！');
            //提交事务
            if ($res) {
                Db:: commit();
                $this->suc('安全培训成功！');
            } else {
                Db::rollback();
                $this->err('安全培训失败！');
            }
        } catch (\Exception $e) {
            Db::rollback();
            $this->err('操作失败！');
        }

    }

    /**
     * 修改用户状态
     */
    public
    function changeUserType()
    {
        $data = [];
        $where = [];
        input('cid') ? $where['id'] = input('cid') : $this->err('缺少用户主键');
        //当前查询用户状态
        $user = model('user')->field('userType')->where($where)->find();

        Db::startTrans();
        try {
            if (!$user) {
                $this->err('用户主键错误！');
            }
            if ($user['userType'] == 1) {
                $data['id'] = $where['id'];
                $data['userType'] = 2;
                model('user')->editData($data, $data['id']);
            } else {
                $data['id'] = $where['id'];
                $data['userType'] = 1;
                model('user')->editData($data, $data['id']);
            }
            $res = model('user')->where(['id' => input('cid')])->find();
            if ($res) {
                Db::commit();
                $this->suc($res);
            } else {
                Db::rollback();
                $this->err('切换失败！');
            }
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $this->err('操作失败！');
        }
    }

    /**
     * 添加同合同
     * status  0-双方都未签署 1-雇主已签 2 双方都签
     */
    public
    function addContract()
    {
        $data = [];
        $res = 0;
        input('orderId') ? $orderId = input('orderId') : $this->err('缺少订单编号！');
        $order = model('order')->where(['signStatus' => 1, 'id' => $orderId])->count();
        if ($order) {
            $this->err('该合同已签署！');
        }
        $data['orderId'] = input('orderId');
        $data['userName'] = input('userName');
        $data['workName'] = input('workName');
        $data['userMobile'] = input('userMobile');
        $data['workMobile'] = input('workMobile');
        $data['startYear'] = input('startYear');
        $data['startMonth'] = input('startMonth');
        $data['startDay'] = input('startDay');
        $data['endYear'] = input('endYear');
        $data['endMonth'] = input('endMonth');
        $data['endDay'] = input('endDay');
        $data['totalAmount'] = input('totalAmount');
        $data['province'] = input('province');
        $data['city'] = input('city');
        $data['district'] = input('district');
        $data['street'] = input('street');
        $data['userIDCards'] = input('userIDCards');
        $data['workerIDCards'] = input('workerIDCards');
        input('userSign') ? $data['userSign'] = input('userSign') : true;
        input('workSign') ? $data['workSign'] = input('workSign') : true;

        $result = $this->validate($data, 'order');
        if ($result !== true) {
            $this->err($result);
        }

        Db::startTrans();
        try {
            if (!input('userSign') && !input('workSign')) {
                $this->err('缺少用户主键！');
            }
            if (input('userSign') && input('workSign')) {
                $data['status'] = 2;
                model('order')->where(['id' => $orderId])->update(['signStatus' => 1]);
                $res = model('user_contract')->where(['orderId' => $orderId])->update($data);
            }
            if (input('userSign') && !input('workSign')) {
                $data['status'] = 1;
                $res = model('user_contract')->editData($data);
            }
            if ($res) {
                Db::commit();
                $this->suc($res);
            } else {
                Db::rollback();
                $this->err('合同添加失败！');
            }
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $this->err('合同添加失败！');
        }

    }

    /**
     * 解除合同
     */
    public
    function cancelContract()
    {
        $where = [];
        input('contractId') ? $where['id'] = input('contractId') : true;

        input('employeeId') ? $employeeId = input('employeeId') : $this->err('缺少雇主主键！');
        input('workId') ? $workId = input('workId') : $this->err('缺少阿姨主键！');

        $relation = model('user_relation')->where(['employeeId' => $employeeId, 'workId' => $workId])->find();
        if (!$relation) {
            $this->err('用户编码错误！');
        }
        //启动事务
        Db::startTrans();
        try {
            if ($relation['isOrder'] == 1 && $relation['isHire'] != 1) {
                if (empty($where['id'])) {
                    $res = model('user_relation')->where(['employeeId' => $employeeId, 'workId' => $workId])->update(['isOrder' => 0, 'trusteeshipStatus' => 0]);
                } else {
                    $contract_res = model('user_contract')->where($where)->find();
                    model('user_contract')->where($where)->delete();
                    $res = model('user_relation')->where(['orderId' => $contract_res['orderId']])->update(['isOrder' => 0, 'trusteeshipStatus' => 0]);
                }
            } elseif ($relation['isOrder'] != 1 && $relation['isHire'] == 1) {
                if (empty($where['id'])) {
                    $res = model('user_relation')->where(['employeeId' => $employeeId, 'workId' => $workId])->update(['isHire' => 0, 'trusteeshipStatus' => 0]);
                } else {
                    $contract_res = model('user_contract')->where($where)->find();
                    model('user_contract')->where($where)->delete();
                    $res = model('user_relation')->where(['orderId' => $contract_res['orderId']])->update(['isHire' => 0, 'trusteeshipStatus' => 0]);
                }
            } else {
                $this->err('用户关系错误！');
            }

            if ($res) {
                //提交事务
                Db::commit();
                $this->suc($res);
            } else {
                //回滚事务
                Db::rollback();
                $this->err('解除合同失败！');
            }
        } catch (\Exception $e) {
            //回滚事务
            Db::rollback();
            $this->err('操作失败！');
        }
    }

    /**
     * 雇主/阿姨关注
     * isFollow   1- 关注
     */
    public
    function follow()
    {
        $where = [];

        input('employeeId') ? $where['employeeId'] = input('employeeId') : $this->err('缺少用户主键！');
        input('workId') ? $where['workId'] = input('workId') : $this->err('缺少用户主键！');
        input('userType') ? $userType = input('userType') : $this->err('缺少用户类型！');

        //数据库中阿姨和雇主是否存在关系
        $relation_res = model('user_relation')->where(['employeeId' => $where['employeeId'], 'workId' => $where['workId']])->find();
        //是否互相关注
        $user_relation = model('user_relation')->where(['employeeId' => $where['employeeId'], 'workId' => $where['workId'], 'isFollow' => 3])->find();
        //雇主关注阿姨查询
        $employee_relation = model('user_relation')->where(['employeeId' => $where['employeeId'], 'workId' => $where['workId'], 'isFollow' => 1])->find();
        //阿姨关注雇主查询
        $work_relation = model('user_relation')->where(['employeeId' => $where['employeeId'], 'workId' => $where['workId'], 'isFollow' => 2])->find();

        if ($userType == 1) {
            //如果已经互相关注或者雇主关注过阿姨
            if (!empty($user_relation) || !empty($employee_relation)) {
                $this->err('已经关注过了！');
            } else {
                //判断阿姨是否关注过雇主
                if (!empty($work_relation)) {
                    //当阿姨已经关注过雇主时
                    $res = model('user_relation')->where(['employeeId' => $where['employeeId'], 'workId' => $where['workId']])->update(['isFollow' => 3]);
                } else {
                    //当阿姨没有关注过雇主时
                    if (empty($relation_res)) {
                        //当雇主阿姨没有任何关系时 执行新增操作
                        $data = [
                            'employeeId' => input('employeeId'),
                            'workId' => input('workId'),
                            'isFollow' => 1,
                            'followTime' => createTime(),
                            'createTime' => createTime()
                        ];
                        $res = model('user_relation')->editData($data);
                    } else {
                        //当雇主阿姨有其他关系时 执行修改操作
                        $res = model('user_relation')->where(['employeeId' => $where['employeeId'], 'workId' => $where['workId']])->update(['isFollow' => 1]);
                    }
                }

            }
        } else {
            //如果已经互相关注或者阿姨关注过雇主
            if (!empty($user_relation) || !empty($work_relation)) {
                $this->err('已经关注过了！');
            } else {
                //判断雇主是否关注过阿姨
                if (!empty($employee_relation)) {
                    //当雇主已经关注过阿姨时
                    $res = model('user_relation')->where(['employeeId' => $where['employeeId'], 'workId' => $where['workId']])->update(['isFollow' => 3]);
                } else {
                    //当雇主没有关注过阿姨时
                    if (empty($relation_res)) {
                        //当雇主阿姨没有任何关系时 执行新增操作
                        $data = [
                            'employeeId' => input('employeeId'),
                            'workId' => input('workId'),
                            'isFollow' => 2,
                            'followTime' => createTime(),
                            'createTime' => createTime()
                        ];
                        $res = model('user_relation')->editData($data);
                    } else {
                        //当雇主阿姨有其他关系时 执行修改操作
                        $res = model('user_relation')->where(['employeeId' => $where['employeeId'], 'workId' => $where['workId']])->update(['isFollow' => 2]);
                    }
                }
            }
        }
        $res ? $this->suc($res) : $this->err('收藏成功！');

    }

    /**
     * 取消关注
     * isFollow
     */
    public
    function cancelFollow()
    {
        $where = [];
        input('employeeId') ? $where['employeeId'] = input('employeeId') : $this->err('缺少用户主键！');
        input('workId') ? $where['workId'] = input('workId') : $this->err('缺少用户主键！');
        input('userType') ? $userType = input('userType') : $this->err('缺少用户类型！');

        //数据库中阿姨和雇主是否存在关系
        $relation_res = model('user_relation')->where(['employeeId' => $where['employeeId'], 'workId' => $where['workId']])->find();
        if (empty($relation_res['isFollow'])) {
            $this->err('尚未关注，请先关注！');
        }
        if ($userType == 1) {
            if ($relation_res['isFollow'] == 1) {
                $res = model('user_relation')->where(['employeeId' => $where['employeeId'], 'workId' => $where['workId']])->update(['isFollow' => 0]);
            } else {
                $res = model('user_relation')->where(['employeeId' => $where['employeeId'], 'workId' => $where['workId']])->update(['isFollow' => 2]);
            }

        } else {
            if ($relation_res['isFollow'] == 2) {
                $res = model('user_relation')->where(['employeeId' => $where['employeeId'], 'workId' => $where['workId']])->update(['isFollow' => 0]);
            } else {
                $res = model('user_relation')->where(['employeeId' => $where['employeeId'], 'workId' => $where['workId']])->update(['isFollow' => 1]);
            }
        }
        $res ? $this->suc('取消成功！') : $this->err('取消失败！');
    }

    /**
     * 语音匹配
     *
     */

    public
    function speechSearch()
    {
        $data = [];
        $res = 0;
        input('voice') ? $voice = input('voice') : $this->err('缺少语音！');
        input('cid') ? $cid = input('cid') : $this->err('缺少用户主键！');
        input('city') ? $city = input('city') : true;
        $user_res = model('user')->where(['id' => $cid])->find();

        $field = 'u.openid,u.id as cid,u.userType,u.province,u.city,u.district, u.avatar,u.street,u.name,u.job as jobId,u.age,u.workCity,DATE_FORMAT(beginTime, \'%H:%i\') as beginTime ,
        DATE_FORMAT(endTime, \'%H:%i\') as endTime, u.workYear,u.workDuty,u.salary,u.rest,j.only,
        u.legalRest,u.introduction,u.pictureSrc1,u.pictureSrc2,u.pictureSrc3,u.videoSrc,u.videoPicSrc,u.appearance,u.isOpenFollow,u.isOpenChat,u.isHiddenMobile,j.name as jobName,
        ur2.isFollow,j.jobSalary,u.isGoodWorker,u.isGoodEmployer';
        //查询用户类型

        $a_field = 'u.openid,u.id as cid,u.userType,u.name,u.avatar,j.only,u.introduction,u.pictureSrc1,u.pictureSrc2,u.pictureSrc3,u.videoSrc,u.videoPicSrc,u.appearance,
        u.isOpenFollow,u.isOpenChat,u.isHiddenMobile,j.name as jobName,ue.ageStart,ue.ageEnd,ue.jobId,ue.province,ue.city,ue.district,ue.street,ue.workCity,ue.beginTime,ue.endTime,ue.workyearStart,ue.workyearEnd,
        ue.workDuty,ue.appearance,ue.salary,ue.rest,ue.legalRest
,ur2.isFollow,j.jobSalary,u.isGoodWorker,u.isGoodEmployer';

        $user = model('user')->field('userType,latitude,longitude')->where(['id' => $cid])->find();
        if (!$user) {
            $this->err('用户编码错误！');
        }

        $job = model('job')->where('')->select();
        foreach ($job as &$value) {
            if (strpos($voice, $value['name']) !== false) {
                $data['id'] = $value['id'];
            }
        }

        if (count($data) == 0) {
            $this->suc('没有该岗位！');
        }

        $where = [
            'u.userStatus' => 1,
            'u.userType' => 2,
            'u.isPushExpect' => 1,
            'u.city' => $user_res['city'],
            'u.job' => $data['id']
        ];
        $a_where = [
            'u.userStatus' => 1,
            'u.userType' => 1,
            'u.isPushExpect' => 1,
            'ue.city' => $user_res['city'],
            'ue.jobId' => $data['id']
        ];

        if (input('city')) {
            $where['u.city'] = input('city');
            $a_where['ue.city'] = input('city');
        }

        switch ($user['userType']) {
            //雇主搜阿姨
            case 1:
                $res = model('user')
                    ->alias('u')
                    ->field($field)
                    ->join('job j ', 'j.id = u.job', 'left')
                    ->join('user_relation ur2', 'u.id = ur2.workId and ' . $cid . ' = ur2.employeeId', 'left')
                    ->where($where)
                    ->order('u.id desc')
                    ->paginate(10)
                    ->toArray();

                break;
            case 2:
                //阿姨搜雇主

                $res = model('user_expect')
                    ->alias('ue')
                    ->field($a_field)
                    ->join('job j', 'j.id=ue.jobId', 'left')
                    ->join('user u', 'u.id = ue.cid', 'left')
                    ->join('user_relation ur2', 'ue.cid = ur2.employeeId and ' . $cid . ' = ur2.workId', 'left')
                    ->where($a_where)
                    ->order('ue.id desc')
                    ->paginate(10)
                    ->toArray();
                break;
            default;
                break;
        }
        $res ? $this->suc($res) : $this->err('没有搜索到相应阿姨！');
    }


    public
    function testPay()
    {

        $data = [];

        /* input('orderId') ? $data['orderId'] = input('orderId') : $this->err('缺少订单主键！');
         input('openid') ? $data['openid'] = input('openid') : $this->err('缺少openid！');
         input('') ? $data[''] = input(' $ucId') : true;*/
        $a = model('pay')->makeWxPreOrder(726, 'o-pL90HbqiorkLxSngWjLAsxIKkQ');
        if ($a['status']) {
            $this->suc($a['content']);
        } else {
            $this->err($a['msg']);
        }
    }

}





